views:

191

answers:

4

I have loaded XmlDocument into memory and created new XmlElement. Now I am trying to add XmlElement to the path /report/section/hosts but I don't know how. I can add it easily below root node of XML but I cannot figure out how can I navigate deeper level in XML and just append there. In pseudo I am trying to do this:

doc.SelectNodes("/report/section/hosts").AppendChild(subRoot);

The code:

        XmlDocument doc = new XmlDocument();

        doc.Load("c:\\data.xml");

        //host
        XmlElement subRoot = doc.CreateElement("host");

        //Name
        XmlElement ElName = doc.CreateElement("name");
        XmlText TxtName = doc.CreateTextNode("text text");
        ElName.AppendChild(TxtName);
        subRoot.AppendChild(ElName);
        doc.DocumentElement.AppendChild(subRoot);

        doc.Save("c:\\data.xml");
+1  A: 

Try SelectSingleNode instead of SelectNodes

XmlElement parent = (XmlElement)doc.SelectSingleNode("/report/section/hosts")
parent.AppendChild(subRoot);
AnthonyWJones
A: 

The SelectNodes method returns a list of Nodes. You should use SelectSingleNode instead...

e.g. (top of my head, did not test in Visual Studio)

doc.SelectSingleNode("/report/section/hosts").AppendChild(subRoot);
Zaagmans
A: 

You need to get a reference to an XmlElement in your doc (other than the root) to append to. There are a number of methods available on XmlDocument such as GetElementById and SelectSingleNode which do this for you in different ways, research to taste.

That said, the whole API in this area is generally regarded as a bit painful, do you have LINQ available?

annakata
A: 

You are almost there. Try using SelectSingleNode instead:

XmlNode node = doc.SelectSingleNode("/report/section/hosts");
node.AppendChild(subRoot);
Jakob Christensen