10

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

Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
Alexander Stalt
  • 977
  • 5
  • 15
  • 22
  • Maybe you should give an example of the xml fragment you want modified, and an example of how you want it to look after modification. It is not clear if you are talking about inserting attribute values or inserting child content or elements. – AaronLS Jan 26 '10 at 07:26
  • i added a xml file but is dissapeared. Is there any restrictions ? Should I use special tags ? – Alexander Stalt Jan 26 '10 at 07:29
  • Just paste the xml in the text of your question and mark it up as code. – Henrik Söderlund Jan 26 '10 at 07:41

4 Answers4

6

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
  • 57,174
  • 8
  • 131
  • 162
3
//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.

How to change XML Attribute

jordanz
  • 367
  • 4
  • 12
Jeeva Subburaj
  • 1,881
  • 2
  • 18
  • 26
  • 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 Jan 26 '10 at 07:18
0
XElement t = XElement.Load("filePath");
t.Element("level").Element("node1").Value = "";
t.Element("level").Element("node2").Value = "";
t.Element("level").Element("node3").Value = "";
t.Save("filePath");
Mehmet
  • 739
  • 1
  • 6
  • 17
-1

Use AppendChild method to inser a child inside a node.

yournode.AppendChild(ChildNode);

link text

Aneef
  • 3,641
  • 10
  • 43
  • 67