How add value on xml in specified node

Total Post:149

Points:1043
C# 
C#
 1270  View(s)
Ratings:
Rate this:

I need write program on c#, which check, if exist node on xml. If not: insert value. So I have tree path: ./a/d and some line, which I need insert:

<e name="aaa" value="bbb" />

How read and insert value in correct place? This is original xml:

 <?xml version="1.0" encoding="utf-8"?>
    <a>
      <b>
      <c></c>
      </b>
    </a>

After , I need XML:

<?xml version="1.0" encoding="utf-8"?>
    <a>
      <b>
      <c></c>
      </b>
      <d>
        <e name="aaa" value="bbb" />
      </d>
    </a>

So, can you help me with code?

  1. Post:412

    Points:2888
    Re: How add value on xml in specified node

    Hi Royce,


    It's easy with LINQ to XML

    var xDoc = XElement.Load("path");
    var elemens =xDoc.Elements("a").First().Element("b");
    element.AddAfterSelf(new XElement("d",
                               new XElement("e", newXAttribute("name","aaa"),
                                                 new XAttribute("value","bbb"))));
    xDoc.Save("path");

      Modified On Apr-04-2018 01:58:33 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!