0

I still cannot find a good solution to process an xml tree like :

<root>
     <lv 1>
        <lv 2>
             <lv 3  d1="h1">
                <lv 4  dd1 = "detail 11">
                <lv 4  dd1 = "detail 12">
             </lv 3>
             <lv 3  d1="h2">
                <lv 4  dd1 = "detail 22">
             </lv 3>
        </lv 2>
     </lv 1>
   </root>

The problem is that I would like to directly go to "lv 3" and build back the relationship :

(h1, detail11) (h1, detail12) (h2, detail22)

I am not so experienced in C# and I have read through some examples and still cannot find out a good solution.

I would be much grateful if anyone can help.

1
  • 1
    This isn't valid XML and no XML tool or API will accept it. Commented Dec 1, 2013 at 13:17

1 Answer 1

1

First, your xml is not an xml, valid representation is the following:

<root>
 <lv1>
    <lv2>
         <lv3  d1="h1">
            <lv4  dd1="detail 11"/>
            <lv4  dd1="detail 12"/>
         </lv3>
         <lv3  d1="h2">
            <lv4  dd1="detail 22"/>
         </lv3>
    </lv2>
 </lv1>
</root>

And having that you can write smth like this:

    var xml = @"<root>
        <lv1>
            <lv2>
                <lv3  d1=""h1"">
                    <lv4  dd1 = ""detail 11""/>
                    <lv4  dd1 = ""detail 12""/>
                </lv3>
                <lv3  d1=""h2"">
                    <lv4  dd1 = ""detail 22""/>
                </lv3>
            </lv2>
        </lv1>
    </root>";

    var doc = new XmlDocument();
    doc.LoadXml(xml);

    foreach (XmlNode lv3Node in doc.SelectNodes("root/lv1/lv2/lv3"))
    {
        foreach (XmlNode lv4Node in lv3Node.SelectNodes("lv4"))
        {
            Console.WriteLine(lv3Node.Attributes["d1"].Value + ";" + lv4Node.Attributes["dd1"].Value);
        }
    }

Output:

h1;detail 11
h1;detail 12
h2;detail 22

C# has 3 ways to work with XML:

  • Linq to XML (based on XDocument) - nice syntax and pretty fast

  • Using DOM (based on XmlDocument) - slow, but allows multiple traversals of the same xml

  • XmlReader - very fast, but cumersome and does not allow going backwards

Sign up to request clarification or add additional context in comments.

1 Comment

A possible solution but maybe <lv x="1"> is more appropriate than <lv1>. The OP should repair the question.

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.