-->

Removing Element from XML in C# [duplicate]

2019-07-27 04:14发布

问题:

This question already has an answer here:

  • How to remove an xml element from file? 3 answers

below is the xml and i need to remove the Element SMS where code equals to "ZOOMLA". i am using C# code as below but it does not work. and gives me "object reference error"

 XDocument doc = XDocument.Parse (xml);
 XElement sms = (from xml2 in doc.Descendants ("SMSList").Descendants ("SMS") where xml2.Attribute ("Code").Value == code select xml2).FirstOrDefault ();
 sms.Remove ();

<?xml version="1.0" encoding="utf-16" ?>
    <Parent>
        <ServiceList />
        <VoiceList />
        <SMSList>
            <SMS>
                <Code>ZOOMLA</Code>
                <Name>Zoom Limited</Name>
                <SubType>Prepaid</SubType>
                <Fields>
                    <Field>
                        <ID>222</ID>
                        <Name>Charges</Name>
                        <CValue>1</CValue>
                        <Priority>0</Priority>
                    </Field>
                </Fields>
            </SMS>
        </SMSList>
        <DataList />
        <LBCOffer />
    </Parent>

回答1:

You're currently looking for a Code attribute, whereas in your XML it's an element. So FirstOrDefault() doesn't find anything and returns null, hence the exception on the next statement.

Additionally, you can just use the LINQ to XML Remove extension method on IEnumerable<T> - that means it will remove all matching elements, so it won't fail if there aren't any. (If you really want to only remove the first match, you could always use Take(1) here.)

XDocument doc = XDocument.Parse(xml);
doc.Descendants("SMSList")
   .Descendants("SMS")
   .Where(x => (string) x.Element("Code") == code)
   .Remove();


回答2:

Code for which you are looking is not an attribute but element whose parent is root element. first load your xml string as XMLDocument and then find the SMS node.

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(@"<?xml version='1.0' encoding='utf-16' ?> <Parent><ServiceList /><VoiceList /><SMSList> <SMS> <Code>ZOOMLA</Code> <Name>Zoom Limited</Name> <SubType>Prepaid</SubType> <Fields><Field><ID>222</ID> <Name>Charges</Name> <CValue>1</CValue> <Priority>0</Priority></Field></Fields></SMS></SMSList><DataList /> <LBCOffer /> </Parent>");
        XmlNode xNode = xmlDoc.SelectSingleNode("/Parent/SMSList/SMS[Code='ZOOMLA']");
        xNode.ParentNode.RemoveChild(xNode);
        XmlDocument xvDoc = xmlDoc;