Reputation: 4198
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
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
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