如何获得的XElement的价值,而不是所有的子节点的值? [英] How to get XElement's value and not value of all child-nodes?

查看:687
本文介绍了如何获得的XElement的价值,而不是所有的子节点的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例XML:

<parent>
<child>test1</child>
<child>test2</child>
</parent>

如果我找parent.Value哪里父的XElement,我得到test1test2。
我所期待的。 (因为无文本/值。

If I look for parent.Value where parent is XElement, I get "test1test2". What I am expecting is "". (since there is no text/value for .

什么性质的XElement的,我应该找谁?

What property of XElement should I be looking for?

推荐答案

当寻找文本数据&LT;父&GT; 元素,你应该寻找有子节点<一href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xobject.nodetype%28v=vs.110%29.aspx\"><$c$c>NodeType性能等于<一个href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlnodetype%28v=vs.110%29.aspx\"><$c$c>XmlNodeType.Text.这些节点将类型<一个href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xtext%28v=vs.110%29.aspx\"><$c$c>XText.下面的示例说明了这一点:

When looking for text data in the <parent> element you should look for child nodes that have NodeType properties equal to XmlNodeType.Text. These nodes will be of type XText. The following sample illustrates this:

var p = XElement
    .Parse("<parent>Hello<child>test1</child>World<child>test2</child>!</parent>");

var textNodes = from c in p.Nodes()
                where c.NodeType == XmlNodeType.Text
                select (XText)c;

foreach (var t in textNodes)
{
    Console.WriteLine(t.Value);
}

更新:如果你想要的是第一个文本节点,如果有的话,这里使用LINQ方法的示例调用,而不是查询COM prehension语法:

Update: if all you want is the first Text node, if any, here's an example using LINQ method calls instead of query comprehension syntax:

var firstTextNode = p.Nodes().OfType<XText>().FirstOrDefault();
if (firstTextNode != null)
{
    var textValue = firstTextNode.Value;
    ...do something interesting with the value
}

注意:第一() FirstOrDefault()将是更好的性能比计数()&GT; 0 在这种情况下。 计数总是枚举整个集合,而 FirstOrDefault()只列举,直到找到一个匹配的。

Note: using First() or FirstOrDefault() will be more performant than Count() > 0 in this scenario. Count always enumerates the whole collection while FirstOrDefault() will only enumerate until a match is found.

这篇关于如何获得的XElement的价值,而不是所有的子节点的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆