简体   繁体   English

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

[英]Get parent element based on value of child element

I have an XDocument object where I am trying to get the direct parent element based on a child element's value. 我有一个XDocument对象,我试图根据子元素的值获取直接父元素。

Getting the child element's value has been no issue, but I am struggling with finding the correct way to get only the parent element. 获取子元素的值一直没有问题,但我正在努力寻找只获取父元素的正确方法。 Having not worked with XML much, I have a suspicion that the solution is simple and I am overthinking it. 由于没有使用过多的XML,我怀疑解决方案很简单,我正在思考它。

Essentially, based on the below XML, if <Active>true</Active> then I want the direct parent element (ie <AlertNotification> ) and no other elements. 基本上,基于以下XML,如果<Active>true</Active>那么我想要直接父元素(即<AlertNotification> )而不需要其他元素。

Thank you in advance. 先感谢您。

An example of the XML 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>

I thinks you should replace the utf-16 in the first line to utf-8 . 我认为你应该将第一行中的utf-16替换为utf-8 Then you may try this: 然后你可以试试这个:

XDocument doc = XDocument.Load(your file);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM