如何仅通过两个文档之间的公共节点进行迭代?
现在,我能够遍历文档的所有节点:
var xmlBody = @"<?xml version="1.0" encoding="UTF-8"?>
<Visit>
<Person>...</Person>
<Name>...</Name>
<Color>...</Color>
</Visit>";
var xdoc = XDocument.Parse(xmlBody);
foreach (XElement child in xdoc.Elements())
{//do stuff}
我想只遍历xdoc.Elements()
和我的nodeList
之间的公共节点:
var nodeList = new List<string> { "Name", "LastName", "Color" };
nodeList
和xdoc
的交集将只是这些节点:名称,颜色:
如何迭代交叉点,就像这样
foreach(XElement child in xdoc.Elements().Intersect(nodeList))
我会使用Linq Where和Contains这样:
var xmlBody = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<Visit>
<Person>...</Person>
<Name>...</Name>
<Color>...</Color>
</Visit>";
var xdoc = XDocument.Parse(xmlBody);
var nodeList = new List<string> { "Name", "LastName", "Color" };
var intersectedElements = xdoc.Elements()
.First() //<Visit>
.Elements()
.Where(element => nodeList.Contains(element.Name.LocalName));
foreach (XElement child in intersectedElements)
{
Console.WriteLine($"{child.Name.LocalName}: {child.Value}");
}
如果你想要嵌套的元素比使用Descendants更深。
var intersectedNestedElements = xdoc.Descendants()
.Where(element => nodeList.Contains(element.Name.LocalName));
foreach (XElement child in intersectedNestedElements)
{
Console.WriteLine($"{child.Name.LocalName}: {child.Value}");
}
两个输出:
Name: ...
Color: ...
您可能应该使用HashSet
而不是列表,然后您可以使用以下Linq根据本地名称过滤掉节点
var nodeNames = new HashSet<string> { "Name", "LastName", "Color" };
foreach(var child in xdoc.Elements().Where(e => nodeNames.Contains(e.Name.LocalName)))
{
// Your code here.
}