简体   繁体   中英

Add multiple child nodes to xml using xpath

I have a xml like below

<ProcessInvoice>
  <ApplicationArea>
    <CreationDateTime>2016-06-01 13:15:36</CreationDateTime>
    <ApplicationGroup>BBEX</ApplicationGroup>
    <MessageType>PROCESSINVOICE</MessageType>
  </ApplicationArea>
</ProcessInvoice>

Now I have path and value to add, but it is dynamic. It can be like following

path-/ProcessInvoice/ApplicationArea/UserArea/Sample1 
value-001

path-/ProcessInvoice/ApplicationArea/UserArea/UserAreaLine/Sample1 
value-002

if the path is present then i have to add the value, else modify the value.

I can split the path and loop through to find till what node is present and what i have to add but I think there might be more elegant way of doing this.Please help me with the best approach to solve this?

Edit Note- I will prefer XDocument And XElement.

May be I didnt explain properly. My xml and node path both are dynamic. There might be situation where multiple nodes are missing from my xml. Now problem is i need to identify upto which node is existing in xml and which nodes i need to create.

Thanks

If "Sample1" node always exist, the code will look like this:

    XmlDocument doc = new XmlDocument();
    doc.Load(FILE);
    var userArea = DocumentElement["ProcessInvoice"]["ApplicationArea"]["UserArea"];

    foreach (XmlNode element in userArea.ChildNodes)
    {
        if (element.Name== "Sample1" )
        {
            XmlNode node == element;
            node.InnerText ="001";
        }
        else if (element.Name == "UserAreaLine")
        {
            XmlNode node == element["Sample1"];
            node.InnerText ="002";
        }

    }

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