Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text value from XDocument?

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?

like image 860
Marshal Avatar asked Dec 16 '22 08:12

Marshal


1 Answers

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)

like image 183
Polity Avatar answered Dec 30 '22 18:12

Polity