HOW ADD VALUE ON XML IN SPECIFIED NODE

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
C# 
C#
 1053  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. Pravesh Singh

    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", new XAttribute("name","aaa"),

                                                 new XAttribute("value","bbb"))));

    xDoc.Save("path");

Answer

NEWSLETTER

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