根据子元素的值获取父元素

3
我有一个XDocument对象,我想根据子元素的值获取直接父元素。获取子元素的值没有问题,但我还在努力找到正确的方法只获取父元素。由于没有经验处理XML,我怀疑解决方案很简单,而我却想得太多了。
基本上,根据下面的XML,如果<Active>true</Active>,那么我只想获取直接父元素(即<AlertNotification>),而不是其他元素。
提前感谢你。
XML示例:
<?xml version="1.0" encoding="utf-16"?>
<Policies xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLschema">
    <PolicyID>1</PolicyID>
    <EmailNotification>
        <Active>false</Active>
    </EmailNotification>
    <AlertNotification>
        <Active>true</Active>
    </AlertNotification>
    <AlarmEnabled>
        <Active>false</Active>
    </AlarmEnabled>
</Policies>

但是 AlertNotification 不包含任何数据。 - Sergey Berezovskiy
1个回答

5

我认为你应该将第一行的 utf-16 替换为 utf-8。然后你可以尝试这样做:

XDocument doc = XDocument.Load(your file);

var elements = doc.Descendants("Active")
                  .Where(i => i.Value == "true")
                  .Select(i => i.Parent);

这个方法提取了 <AlertNotification><Active>true</Active></AlertNotification>,但我能够从中仅提取父元素。谢谢! - TestK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接