鉴于下面的工作代码段,我正在尝试在target
中获取RootChild2
元素。
https://dotnetfiddle.net/eN4xV9
string str =
@"<?xml version=""1.0""?>
<!-- comment at the root level -->
<Root>
<RootChild1>
<Child>Content</Child>
<Child>Content</Child>
<Child>Content</Child>
</RootChild1>
<RootChild2>
<Child>Content</Child>
<Child key='target'>Content</Child>
<Child>Content</Child>
</RootChild2>
</Root>";
XDocument doc = XDocument.Parse(str);
foreach (XElement element in doc.Descendants("RootChild2"))
{
if (element.HasAttributes && element.Element("Child").Attribute("key").Value == "target")
Console.WriteLine("found it");
else
Console.WriteLine("not found");
}
这里有三个问题:
RootChild2
元素是否具有任何属性-并没有Child
元素下的第一个RootChild2
元素XAttribute
)这里的代码将在RootChild2
中找到all目标元素:
foreach (XElement element in doc.Descendants("RootChild2"))
{
var targets = element
.Elements("Child")
.Where(child => (string) child.Attribute("key") == "target")
.ToList();
Console.WriteLine($"Found {targets.Count} targets");
foreach (var target in targets)
{
Console.WriteLine($"Target content: {target.Value}");
}
}
请注意,将XAttribute
强制转换为string
是避免空引用问题的一种简单方法-因为当源为null时,显式转换的结果为null。 (这是LINQ to XML中的通用模式。)
您正在通过循环内的element
访问RootChild2-Element本身。看看以下版本:
foreach (XElement element in doc.Descendants("RootChild2").Nodes())
{
if (element.HasAttributes && element.Attribute("key").Value == "target")
Console.WriteLine("found it");
else
Console.WriteLine("not found");
}
现在,它遍历RootChild2的所有节点。
一点点重写foreach
循环并添加空检查
foreach (XElement element in doc.Descendants("RootChild2").Elements())
{
if (element.HasAttributes && element.Attribute("key")?.Value == "target")
Console.WriteLine("found it");
else
Console.WriteLine("not found");
}
这将找到所有3个RootChild2/Child
元素,然后依次测试每个元素:
foreach (XElement child in doc.Descendants("RootChild2").Elements("Child"))
{
if ((string)child.Attribute("key") == "target")
Console.WriteLine("found it");
else
Console.WriteLine("not found");
}