简体   繁体   English

如何从XDocument获取文本值?

[英]How to get text value from XDocument?

I'm having an XDocument.For example, 我有一个XDocument。例如,

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

How to get the text value from the XDocument? 如何从XDocument获取文本值? How to identify the textvalue among the elements? 如何识别元素中的textvalue

Text values are interpreted by XLinq as XText. XLinq将文本值解释为XText。 therefore you can easily check if a node is of type XText or by checking the NodeType see: 因此,您可以轻松检查节点是否为XText类型,或者通过检查NodeType,请参阅:

// 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: 您可以检查父项是否命名为“name”,或者textNode本身是否单独或不显示:

// 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. 编辑一个额外的评论,我看到许多人声称这个XML无效。 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. 您可以使用Nodes属性迭代文档根元素的子节点。 From there on, text nodes will be represented by XText instances, and their text value is available through their Value property: 从那时起,文本节点将由XText实例表示,其文本值可通过其Value属性获得:

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

Assuming the variable "doc" contains the XDocument representing your XML above, 假设变量“doc”包含表示上面的XML的XDocument,

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. 这应该为您提供包含您正在查找的纯文本的所有XText类型文本节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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