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>
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.
You're currently looking for a
Code
attribute, whereas in your XML it's an element. SoFirstOrDefault()
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 onIEnumerable<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 useTake(1)
here.)