I'm having an XDocument.For example,
<cars>
<name>
<ford>model1</ford>
textvalue
<renault>model2</renault>
</name>
</cars>
How to get the text value from the XDocument? How to identify the textvalue among the elements?
Text values are interpreted by XLinq as XText. therefore you can easily check if a node is of type XText or by checking the NodeType see:
// get all text nodes
var textNodes = document.DescendantNodes()
.Where(x => x.NodeType == XmlNodeType.Text);
However, it strikes me that you only want to find that piece of text that seems a bit lonely named textvalue. There is no real way to recognize this valid but unusual thing. You can either check if the parent is named 'name' or if the textNode itself is alone or not see:
// get 'lost' textnodes
var lastTextNodes = document.DescendantNodes()
.Where(x => x.NodeType == XmlNodeType.Text)
.Where(x => x.Parent.Nodes().Count() > 1);
edit just one extra comment, i see that many people claim that this XML is invalid. I have to disagree with that. Although its not pretty, it's still valid according to my knowledge (and validators)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With