Home > DeveloperSection > Forums > How add value on xml in specified node
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    January-27-2014 2:58 AM

 C# C# 
Ratings:


 1 Reply(s)
 767  View(s)
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?



Pravesh Singh

Total Post:411

Points:2881
Posted on    January-27-2014 3:17 AM

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");


Don't want to miss updates? Please click the below button!

Follow MindStick