Mikk
Mikk

Reputation: 455

Adding an element to this xml structure

<root>
    <element1>innertext</element1>
    <element2>innertext</element2>
    <element3>
        <child1>innertext</child1>
    </element3>
</root>

I have an xml structure shown above.

I would like to "append" the xml file (it is already created) to add another "child" inside element3>, so that it will look like this:

<root>
    <element1>innertext</element1>
    <element2>innertext</element2>
    <element3>
        <child1>innertext</child1>
        <child2>innertext</child2>
    </element3>
</root>

Linq to xml and/or Xpath would be great

EDIT: I have tried doing this:

XElement doc = XElement.Load(mainDirectory);
XElement newElem = doc.Elements("element3").First();
newElem.Add(new XElement("child2", "child2innertext"));
doc.Add(newElem);
doc.Save(mainDirectory); 

Upvotes: 1

Views: 216

Answers (3)

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

With XDocument you can achieve this as:

 string xml = "<root><element1>innertext</element1><element2>innertext</element2><element3><child1>innertext</child1></element3></root>";

 var doc = XDocument.Parse(xml); //use XDocument.Load("filepath"); in case if your xml is in a file.

 var el3 = doc.Descendants("element3").FirstOrDefault();

 el3.Add(new XElement("child2", "innertext"));

Upvotes: 2

Michael Barabash
Michael Barabash

Reputation: 103

Please, try this LINQPAD example

void Main()
{
var xml = 
@"<root>
        <element1>innertext</element1>
        <element2>innertext</element2>
        <element3>
            <child1>innertext</child1>
        </element3>
    </root>";

    var doc = XDocument.Parse(xml); 
    doc.Root.Element("element3")
    .Add(new XElement("child2", "innertext"));

    doc.Dump();
}

Upvotes: 1

Murali N
Murali N

Reputation: 3498

XmlDocument xDoc = new XmlDocument();
        xDoc.Load("filename.xml");

        foreach (XmlNode xNode in xDoc.SelectNodes("/root/element3"))
        {
            XmlElement newElement = xDoc.CreateElement("Child2");


            xNode.AppendChild(newElement);
            xNode.InnerText = "myInnerText";
        }

Upvotes: 3

Related Questions