Search code examples
c#textxmlreaderxmlnode

How read a specific XmlNode without knowing its name


couldn't find a specific answer to that

Here is an Xml example for my problem

<Rectangle>
    <elementcolor>blue</elementcolor>
    <elementwidth>200</elementwidth>
</Rectangle>
<Line>
    <elementcolor>red</elementcolor>
    <elementwidth>150</elementwidth>
</Line>

I want to get all the elements that have ChildNodes, and i don't want to get those who have simple text

I want to put into a list, in this example, Rectangle and Line.

But when asking .HasChildNodes to those nodes which contains simple text they return me True and as ChildNode[0].Name they return me "#text".

I can't simply asking .HasChildNodes, and i couldn't find other way to specify which node has a Node as ChildNode and which one has a "#text"

So i tried using XmlReader, this way:

XmlTextReader reader = new XmlTextReader(file);
while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        list.Add(reader.Name);   
    }
}

This is returning me all Xml nodes, but i just want those who have a Node as ChildNode, how can i do that?

Thanks in advance


Solution

  • You can use linq2xml for that...

    var xml = @"<wrapper>
    <Rectangle>
        <elementcolor>blue</elementcolor>
        <elementwidth>200</elementwidth>
    </Rectangle>
    <Rectangle/>
    <Line/>
    <Line>
        <elementcolor>red</elementcolor>
        <elementwidth>150</elementwidth>
    </Line>
    </wrapper>";
    
    var elements = XElement
        .Parse(xml)
        .Descendants()
        .Where(o => o.HasElements);
    elements.Dump();
    

    OUTPUT

    <Rectangle>
      <elementcolor>blue</elementcolor>
      <elementwidth>200</elementwidth>
    </Rectangle> 
    <Line>
      <elementcolor>red</elementcolor>
      <elementwidth>150</elementwidth>
    </Line>