tags:

views:

165

answers:

3

I have a xml-file:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
  <level>
    <node1 />
    <node2 />
    <node3 />
  </level>
</root>

What is the simplest way to insert values in node1, node2, node3 ?

C#, Visual Studio 2005

A: 
//Here is the variable with which you assign a new value to the attribute
    string newValue = string.Empty 
    XmlDocument xmlDoc = new XmlDocument();

    xmlDoc.Load(xmlFile);

    XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
    node.Attributes[0].Value = newValue;

    xmlDoc.Save(xmlFile);

Credit goes to Padrino

http://stackoverflow.com/questions/367730/how-to-change-xml-value-file-using-c

Jeeva S
This updates an existing attribute value, not 'inserting' as what the OP asked for. Nevertheless the question is not very specific too.
o.k.w
+1  A: 

Here you go:

XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(@"
    <root>
        <level>
            <node1 />
            <node2 />
            <node3 />
        </level>
    </root>");
XmlElement node1 = xmldoc.SelectSingleNode("/root/level/node1") as XmlElement;
if (node1 != null)
{
    node1.InnerText = "something"; // if you want a text
    node1.SetAttribute("attr", "value"); // if you want an attribute
    node1.AppendChild(xmldoc.CreateElement("subnode1")); // if you want a subnode
}
Rubens Farias
A: 

Use AppendChild method to inser a child inside a node.

yournode.AppendChild(ChildNode);

link text

Aneef