Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting XML Element after last specific node/element

I want to add elements after last child in the XML. But I got an error.

<XML ID="Microsoft Search Thesaurus">
  <thesaurus xmlns="x-schema:tsSchema.xml">
    <diacritics_sensitive>0</diacritics_sensitive>
    <expansion>
        <sub>Internet Explorer</sub>
        <sub>IE</sub>
        <sub>IE5</sub>
    </expansion>
    <replacement>
        <pat>NT5</pat>
        <pat>W2K</pat>
        <sub>Windows 2000</sub>
    </replacement>
    <expansion>
        <sub>run</sub>
        <sub>jog</sub>
    </expansion>
    <expansion>
      <sub>home</sub>
      <sub>house</sub>
    </expansion>
  </thesaurus>
</XML>

My code is below and I encounter this error, when I debug the code.

InvalidOperationException was unhandled.

Sequence contains no elements.

XDocument doc = XDocument.Load("tseng.xml");  //load the xml file.
IEnumerable<XElement> MemberList = doc.Element("XML").Elements("thesaurus");
var Member = new XElement("expansion",
                 new XElement("sub", "home"),
                 new XElement("sub", "house")
             );
MemberList.Last().AddAfterSelf(Member);  //add node to the last element.
doc.Save("tseng.xml");

This error is for specific line:

MemberList.Last().AddAfterSelf(Member);

I don't know what is my problem on this code. How can I add element after last <expansion> node to my XML file?

Can you help me for this problem? Thanks.

like image 702
mkacar Avatar asked Jan 22 '12 19:01

mkacar


1 Answers

The <thesaurus> element has an xmlns attribute that specifies a namespace, so you need to add the namespace to all the element names. Also, you should use Add instead of AddAfterSelf if you want the new <expansion> element to appear inside <thesaurus> instead of after it.

XNamespace ns = "x-schema:tsSchema.xml";
IEnumerable<XElement> MemberList = doc.Element("XML").Elements(ns + "thesaurus");
var Member = new XElement(ns + "expansion",
                 new XElement(ns + "sub", "home"),
                 new XElement(ns + "sub", "house"));
MemberList.Last().Add(Member);  //add node to the last element. 
like image 161
Michael Liu Avatar answered Oct 09 '22 11:10

Michael Liu