0

I want to create a routing(path) to xml element and assign it to a variable so i can access it fast in the future. The element, which is a child of other elements, can change its position in the document so i cant use methods like first child or indexing that rely on position. The path to the element will always stay constant and there is no other path like it. If we look at a short example so i want a path to level4 value(header4) so i can modify it.

    <level1>
    <level2>
        <level3>header3</level3>
            <level4>header4</level4>
        <level3>header31</level31>
    </level2>
    <level2>
        <level3>nnn</level3>
        <level3>nnnnn</level31>
    </level2>
</level1>
1
  • @AlexeiLevenkov lol whoops. Silly me. Been a long day. Commented Sep 26, 2012 at 21:20

2 Answers 2

3

You've got to use XPath in that case.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Path of the xml");
XmlNode titleNode = xmlDoc.SelectSingleNode("//level1/level2/level3");
Sign up to request clarification or add additional context in comments.

Comments

1

You can use XPath for this.

XmlDocument doc; // assuming the xml is already in doc
XmlNode node = doc.SelectSingleNode("/level1/level2/level3/level4");
if(node != null) 
{
    node.InnerText = "New value";
}

If there could be more than one level4 then you could do this:

XmlDocument doc; // assuming the xml is already in doc
XmlNodeList nodes = doc.SelectNodes("/level1/level2/level3/level4");
if(nodes != null) 
{
    foreach(XmlNode node in nodes)
    {
        node.InnerText = "New value";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.