简体   繁体   中英

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?

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)

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM