C # Identify parent, child elements in XML file

I found this on the 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 above would be

food
child
nested
child
other

      

This works great, I just need to determine which elements contain children.

for example i need this output

startParent_food
    startParent_child
        nested
    endParent_child
    startParent_child
        other
    endParent_child
endParent_food

      

+3


source to share


2 answers


You can do it with XmlReader

, but it won't be that easy. You can't know if an element has children without continuing to read on, so you'll need to buffer and keep track of various things (since XmlReader

it's for forwarding only). Unless you have a reason to use such a low-level API, I highly recommend that you avoid it.

It's pretty 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 implied in your comment, your actual requirement is to change some of the values, then you can do so without having to handle the details of the XML structure. For example, to change the value of your element nested

:

var doc = XDocument.Parse(xml);

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

target.Value = "some text";

var result = doc.ToString();

      

See this fiddle for a demonstration of both.

+4


source


For checking children, your code would look something like this:

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

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

      



you will need to make it recursive in order to check all elements.

0


source







All Articles