Reputation: 333
I have an XDocument object where I am trying to get the direct parent element based on a child element's value.
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.
Essentially, based on the below XML, if <Active>true</Active>
then I want the direct parent element (i.e. <AlertNotification>
) and no other elements.
Thank you in advance.
An example of the 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>
Upvotes: 3
Views: 4881
Reputation: 32481
I thinks you should replace the utf-16
in the first line to 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);
Upvotes: 6