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>
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();