简体   繁体   中英

Adding child nodes to a node in XML using Linq To excel

Following is the structure of my XML

<Id>
 <Sid> 123 </Sid>
 <Name> Xyz </Name>
 <Name> Abc </Name>
</Id>
<Id>
 <Sid> 789 </Sid>
 <Name> Xyz </Name>
 <Name> Abc </Name>
</Id>

I just want to Enter a new child node ie Any Name to the node which is having value Sid = 789.

I have tried this code but its not working.

XElement xe = xDoc.Elements().Where(r => (string)r.Element("Sid") == "789").FirstOrDefault();

            xe.Add(new XElement("Name", "Hello")); 

Since im new to Linq and Excel ,i am unable to figure it out.

Can anyone please help me to understand this and achieve a postive result.

All sort of help will be appreciated.

Thanks and regards.

You can try to use XPath query expression to select element with complex criteria :

using System.Xml.XPath;

........
........
XElement xe = xDoc.XPathSelectElement("//Id[Sid=123]");
xe.Add(new XElement("Name", "Hello")); 

or without XPath * :

XElement xe = xDoc.Root.Elements()
                    .Where(r => (string)r.Element("Sid") == "789")
                    .FirstOrDefault();
xe.Add(new XElement("Name", "Hello")); 

*) I assume that <Id> elements are direct child of a root node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM