jiya ali
jiya ali

Reputation: 43

C# Identify parent,child elements in XML file

I found this on internet.

string xml = @"
<food>
  <child>
    <nested />
  </child>
  <child>
    <other>
    </other>
  </child>
</food>
";

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
  if (rdr.NodeType == XmlNodeType.Element)
  {
  Console.WriteLine(rdr.LocalName);
  }
}

The result of the above will be

food
child
nested
child
other

This is working perfect, Just i need to identify which elements contains child elements.

for example, I need this output

startParent_food
    startParent_child
        nested
    endParent_child
    startParent_child
        other
    endParent_child
endParent_food

Upvotes: 3

Views: 1179

Answers (2)

Charles Mager
Charles Mager

Reputation: 26223

You can do this with XmlReader, but it won't be particularly easy. You can't know if an element has children without continuing to read further, so you'd have to buffer and track various things (as XmlReader is forward-only). Unless you have a good reason to use such a low level API then I'd strongly suggest you avoid it.

This is fairly trivial with LINQ to XML

private static void Dump(XElement element, int level)
{
    var space = new string(' ', level * 4);

    if (element.HasElements)
    {
        Console.WriteLine("{0}startParent_{1}", space, element.Name);

        foreach (var child in element.Elements())
        {
            Dump(child, level + 1);
        }

        Console.WriteLine("{0}endParent_{1}", space, element.Name);
    }
    else
    {
        Console.WriteLine("{0}{1}", space, element.Name);
    }
}

If, as you imply in your comment, your actual requirement is to modify some values then you can do this without any need to process the details of the XML structure. For example, to modify the value of your nested element:

var doc = XDocument.Parse(xml);

var target = doc.Descendants("nested").Single();

target.Value = "some text";

var result = doc.ToString();

See this fiddle for a demo of both.

Upvotes: 4

Ali Ashraf
Ali Ashraf

Reputation: 119

For checking child elements, your code will look something like below:

    System.Xml.Linq.XElement _x;
    _x = System.Xml.Linq.XElement.Parse(xml);

    if (_x.HasElements)
    {
        // your req element
    }

you will have to make it recursive to check all elements.

Upvotes: 0

Related Questions