LINQ to XML-获得给定的XElement的文本内容,而没有子元素的文本内容 [英] LINQ to XML - Get given XElement's text content without child elements' text content
问题描述
我刚刚开始使用 LINQtotoXML ,以及在获取给定XElement的文本内容而不同时获取所有子元素的文本内容时,我遇到了麻烦.
I have just started using LINQ to XML, and I am having trouble getting the text contents of a given XElement without getting the text contents of all the child elements as well.
例如,如果我有以下XML文档:
So for example, if I have the following XML document:
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="example.org/rootns">This is root value
<children>
<child name='child 1'>value 1</child>
<child name='child 2'>value 2
<grandchild name='grandchild A'>value A</grandchild>
</child>
</children>
</root>
我使用以下测试方法:
private static void Test()
{
string xString = @"<?xml version=""1.0"" encoding=""utf-8"" ?><root xmlns=""example.org/rootns"">This is root value<children><child name='child 1'>value 1</child><child name='child 2'>value 2<grandchild name='grandchild A'>value A</grandchild></child></children></root>";
var xDoc = XDocument.Parse(xString);
XNamespace ns = @"example.org/rootns";
string elemName = "child";
var xElems = from e in xDoc.Descendants(ns + elemName)
select e;
foreach (var xElem in xElems)
{
Console.WriteLine(xElem.Value);
}
}
然后我在输出中得到两行:
Then I get two lines on output:
value 1
value 2value A
第一行显示第一个孩子的内容-可以.但是第二行不仅显示第一个孩子的文本内容,还显示该孩子的所有后代.
The first line shows the content of the first child - this is okay. The second line however shows not only the text content of the first child, but also any decendants of that child.
如何获得第二个孩子的文本内容而又没有孙子的文本内容?
How can I get the text content of just the second child without the grandchild's text content as well?
还要注意,该示例只是一个简单的示例,用于说明我在做什么,在生产中,我不一定知道子元素的名称(如果有),但是我应该能够获得所需的元素从中获取文本内容.
Also note that the sample is just a simple example to illustrate what I am doing, and in production I will not necessarily know what the child elements are called (if any), but I should be able to get the element I need to get the text content from.
Jon Skeet的回答为解决方案提供了帮助.只需将foreach循环替换为以下内容即可选择文本XNode而不是XElement的值:
Jon Skeet's answer helped with the solution. Just replace the foreach loop with the following to select text XNodes rather than the XElement's value:
...
foreach (var xElem in xElems)
{
var values = from n in xElem.Nodes()
where n.NodeType == System.Xml.XmlNodeType.Text
select n;
if (values != null && values.Count() > 0)
Console.WriteLine(values.First());
}
推荐答案
如果存在多个多个文本节点,您想怎么办?例如,您可以将它们全部结合在一起:
What do you want to do if there are multiple text nodes? For example, you could join them all together:
var text = string.Join("", element.Nodes.OfType<XText>().Select(x => x.Value));
如果只需要一个元素,则比显示的要容易:
If you only want a single element, it's easier than you've shown:
var textNode = xElem.Nodes().OfType<XText>().FirstOrDefault();
if (textNode != null)
{
Console.WriteLine(textNode.Value);
}
这篇关于LINQ to XML-获得给定的XElement的文本内容,而没有子元素的文本内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!