XDocument Descendants()在父节点中显示所有子值 [英] XDocument Descendants() displays all child values in the parent node
本文介绍了XDocument Descendants()在父节点中显示所有子值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是要使用XDocument解析的XML:
This is the XML to be parsed, using XDocument:
<e xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FormValues />
<Others>
<Bank>
<Key>FirstKey</Key>
<Value>FirstValue</Value>
</Bank>
<Bank>
<Key>SecondKey</Key>
<Value>SecondValue</Value>
</Bank>
<Bank>
<Key>ThirdKey</Key>
<Value>ThirdValue</Value>
</Bank>
<Bank>
<Key>FourthKey</Key>
<Value>FourthValue</Value>
</Bank>
</Others>
<Prob>ProbValue</Prob>
<URL>http://example.com/</URL>
<Method>GET</Method>
</e>
如果我这样做:
string doc = "<e xmlns:xsd..> ..... </e>";
System.Xml.Linq.XDocument docNew = System.Xml.Linq.XDocument.Parse(doc);
var elements = docNew.Root.Descendants();
@foreach (var element in elements)
{
<label>@element.Name.ToString():</label><span>@element.Value.ToString()</span>
}
它显示:
FormValues:
Others: FirstKeyFirstValueSecondKeySecondValueThirdKeyThirdValueFourthKeyFourthValue
Bank : FirstKeyFirstValue
Key : FirstKey
Value: FirstValue
Bank : SecondKeySecondValue
Key : SecondKey
Value: SecondValue
Bank : ThirdKeyThirdValue
Key : ThirdKey
Value: ThirdValue
Bank : FourthKeyFourthValue
Key : FourthKey
Value: FourthValue
Prob : ProbValue
URL : http://example.com/
Method:GET
我只希望键和值节点显示值.喜欢:
I only want the Key and Value Nodes to display the value. Like:
Others
Bank
Key : FirstKey
Value: FirstValue
Bank
Key : SecondKey
Value: SecondValue
....
推荐答案
XText
每个 XElement
所拥有的子节点直接.(这些节点拥有实际的字符数据)元素.)
XElement.Value
returns a string that contains all of the text content of this element, but you want to display just the concatenated value(s) of the XText
child nodes directly owned by each XElement
. (These are the nodes that hold the actual character data of an element.)
这可以如下进行:
var docNew = System.Xml.Linq.XDocument.Parse(doc);
foreach (var element in docNew.Root.Descendants())
{
var textValue = string.Concat(element.Nodes().OfType<System.Xml.Linq.XText>().Select(tx => tx.Value));
Console.WriteLine(string.Format("{0}: {1}", element.Name.ToString(), textValue));
}
此逻辑可以提取为扩展方法:
This logic can be extracted into an extension method:
public static partial class XNodeExtensions
{
public static string LocalValue(this XContainer node)
{
if (node == null)
return null;
return string.Concat(node.Nodes().OfType<XText>().Select(tx => tx.Value));
}
}
并按如下方式使用:
var textValue = element.LocalValue();
它打印以下内容:
FormValues:
Others:
Bank:
Key: FirstKey
Value: FirstValue
Bank:
Key: SecondKey
Value: SecondValue
Bank:
Key: ThirdKey
Value: ThirdValue
Bank:
Key: FourthKey
Value: FourthValue
Prob: ProbValue
URL: http://example.com/
Method: GET
演示小提琴此处.
这篇关于XDocument Descendants()在父节点中显示所有子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文