Removing Element from XML in C# [duplicate]

你说的曾经没有我的故事 提交于 2019-12-24 13:09:31

问题


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;


来源:https://stackoverflow.com/questions/27619686/removing-element-from-xml-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!