How to get text value from XDocument?

I have an XDocument. For instance,

<cars> <name> <ford>model1</ford> textvalue <renault>model2</renault> </name> </cars> 

How to get text value from XDocument? How to identify text value among elements?

+4
source share
3 answers

Text values ​​are interpreted by XLinq as an XText. so you can easily check if there is a node of type XText or by checking NodeType:

 // get all text nodes var textNodes = document.DescendantNodes() .Where(x => x.NodeType == XmlNodeType.Text); 

However, it seems to me that you only want to find that part of the text that seems a little lonely with the name textvalue. There is no real way to recognize this real, but unusual thing. You can either check if the parent has the name 'name', or if the textNode itself is alone or does not see:

 // get 'lost' textnodes var lastTextNodes = document.DescendantNodes() .Where(x => x.NodeType == XmlNodeType.Text) .Where(x => x.Parent.Nodes().Count() > 1); 

edit only one additional comment, I see that many people claim that this XML is invalid. I do not agree with that. Although not very pretty, it still acts in accordance with my knowledge (and validators)

+9
source

You can use the Nodes property to iterate over the child nodes of the document root element. From there, the text nodes will be represented by XText instances, and their text value is available through their Value :

 string textValue = yourDoc.Root.Nodes.OfType<XText>().First().Value; 
+3
source

Assuming the doc variable contains an XDocument representing your XML above,

 doc.XPathSelectElement("cars/name").Nodes().OfType<XText>() 

This should give you all the text nodes of type XText that contain the plain text you are looking for.

0
source

All Articles