Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

Check if xml node contains simple text or other element

I have a question I have a simple xml:

<Event>
  <Value>Some Text</Value>
  <Value>
    <Solution Flag="1" />
  </Value>
</Event>

Value allays contains one child text or different node.

And simple process:

 const string xml = @"<Event><Value>Some Text</Value><Value><Solution Flag = ""1""/></Value></Event>";
 XDocument xDocument = XDocument.Parse(xml);
 IEnumerable<XElement> xPath = xDocument.XPathSelectElements($"//Event");
 foreach (XElement xElement in xPath)
 {
     // check if xElement child is a string or x element
 }

Now what I am trying to do is iterate each xElement in event and check if node (Value) is text or different x element, but I do knot know exactly hot to do that. Any ideas?

Upvotes: 3

Views: 1420

Answers (2)

Sylwester Santorowski
Sylwester Santorowski

Reputation: 197

The xElement.FirstNode is XText would do the job. The working example:

public static void TestForStackOverflow()
{
        const string xml = @"<Event><Value>Some Text</Value><Value><Solution Flag = ""1""/></Value></Event>";
        XDocument xDocument = XDocument.Parse(xml);
        IEnumerable<XElement> xPath = xDocument.XPathSelectElements(@"//*");
        foreach (XElement xElement in xPath)
        {
            Console.Write("{0}     {1}", xElement.Name.LocalName, xElement.NodeType.ToString());
            // check if xElement child is a string or x element
            if (xElement.FirstNode is XText)
                Console.Write("   has XText");
            Console.WriteLine();
        }
}

Upvotes: 1

dimitar.d
dimitar.d

Reputation: 653

xDocument.XPathSelectElements($"//Event"); returns all elements with the specified tag (<Event>). For each element you need to check its children whether or not they have elements within. As pointed by @蕭為元 you can use child.HasElements property:

IEnumerable<XElement> xPath = xDocument.XPathSelectElements($"//Event");
foreach (XElement xElement in xPath)
{
       var xElementChildren = xElement.Elements();
       foreach (var child in xElementChildren)
       {
              if (child.HasElements)
              {
                            // your logic
              }
       }             
}

Upvotes: 1

Related Questions