C# 遍历 XDocument 中的每个 XElement
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15433732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through each XElement in an XDocument
提问by doosh
I have an XML that looks like this:
我有一个如下所示的 XML:
<myVal>One</myVal>
<myVal>Two</myVal>
<myVal>Three</myVal>
<myVal>Four</myVal>
<myVal>Five</myVal>
I want to load that into an XDocument and then iterate through each XElement in that XDocument and count the number of characters in each element.
我想将其加载到 XDocument 中,然后遍历该 XDocument 中的每个 XElement 并计算每个元素中的字符数。
What is the best way of doing that?
这样做的最佳方法是什么?
First off, I noticed I have to add a root element or XDocument.Parse() would not be able to parse it as XML. So I added:
首先,我注意到我必须添加一个根元素,否则 XDocument.Parse() 将无法将其解析为 XML。所以我补充说:
<span>
<myVal>One</myVal>
<myVal>Two</myVal>
<myVal>Three</myVal>
<myVal>Four</myVal>
<myVal>Five</myVal>
</span>
But then when I do:
但是当我这样做时:
foreach (XElement el in xDoc.Descendants())
el
will contain the entire XML, starting with the first <span>
, including each and every one of the <myVal>
s and then ending with </span>
.
el
将包含整个 XML,从第一个 开始<span>
,包括每个<myVal>
s,然后以</span>
.
How do I iterate through each of the XML elements (<myVal>One</myVal>
etc) using XDocument?
如何<myVal>One</myVal>
使用 XDocument遍历每个 XML 元素(等)?
I don't know on beforehand what all the XML elements will be named, so they will not always be named "myVal".
我事先不知道所有 XML 元素将被命名为什么,因此它们不会总是被命名为“myVal”。
采纳答案by Bennor McCarthy
Use doc.Root.Elements()
(for direct children of the root node, which I think is really what you want) or doc.Root.Descendants()
(if you want every descendant, including any possible child of <myVal/>
).
使用doc.Root.Elements()
(用于根节点的直接子节点,我认为这确实是您想要的)或doc.Root.Descendants()
(如果您想要每个子节点,包括 的任何可能的子节点<myVal/>
)。
回答by CodeGuru
Do like this :
这样做:
string xml = " <span><myVal>One</myVal><myVal>Two</myVal><myVal>Three</myVal><myVal>Four</myVal><myVal>Five</myVal></span>";
XmlReader xr = XmlReader.Create(new StringReader(xml));
var xMembers = from members in XElement.Load(xr).Elements() select members;
foreach (XElement x in xMembers)
{
var nodeValue = x.Value;
}
Now if you see the value of nodeValueyou will get One Two etc
现在,如果您看到nodeValue的值, 您将得到一二等