【问题标题】:Get parent element based on value of child element根据子元素的值获取父元素
【发布时间】:2013-12-13 15:01:39
【问题描述】:

我有一个 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不包含任何数据

标签: c# xml linq-to-xml


【解决方案1】:

我认为您应该将第一行中的utf-16 替换为utf-8。那你可以试试这个:

XDocument doc = XDocument.Load(your file);

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

【讨论】:

  • 这个方法提取了&lt;AlertNotification&gt;&lt;Active&gt;true&lt;/Active&gt;&lt;/AlertNotification&gt;,但我只能从那里提取父元素。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多