c# - Linq to XML 通过查询子元素获取父元素属性值

标签 c# linq linq-to-xml predicatebuilder

我正在尝试构建 Linq to XML 查询,但尚未找到真正的解决方案。

这是我的 XML

<Nodes>
  <Node Text="Map" Value="Map">
    <Node Text="12YD" Value="12YD">
      <Node Text="PType" Value="PType">
        <Node Text="12" Value="12" />
      </Node>
      <Node Text="SType" Value="SType">
        <Node Text="2" Value="2" />
      </Node>
    </Node>
    <Node Text="12YP" Value="12YP">
      <Node Text="PType" Value="PType">
        <Node Text="12" Value="12" />
      </Node>
      <Node Text="SType" Value="SType">
        <Node Text="1" Value="1" />
      </Node>
    </Node>
  </Node>
</Nodes>

我可用的参数适用于 PType 节点和 SType 节点,现在根据它们的值我需要获取父节点属性值。

Example:

Params: {PType:12}, {SType:2} should give me 12YD as a result.  
Params: {PType:12}, {SType:1} should give me 12YP as a result.

我尝试了不同的解决方案,甚至使用 PredicateBuilder 但没有成功。任何帮助将不胜感激。

这是我使用 LinqPad 的最新代码。

void Main()
{
    var xml = XElement.Load (@"C:\map.xml");

    string value = "{PType:12},{SType:1}";
    string[] mapReqValues = value.Split(',');

    var predicate = PredicateBuilder.False<XElement>();
    foreach (string r in mapReqValues)
    {
        var m = Regex.Match(r, @"{([^}]+)}").Groups[1].Value.Split(':');
        predicate = predicate.Or(p => p.Attribute("Value").Value == m[0] && 
            p.Descendants().Attributes("Value").FirstOrDefault().Value == m[1]);

    }

    var result = xml.Descendants().AsQueryable().Where(predicate);
    result.Dump();
}

最佳答案

XDocument xDoc = XDocument.Load(new StringReader(xml));    

var Tuples = xDoc.Descendants("Node").Where(n => n.Attribute("Text").Value == "PType")
            .Join(
                xDoc.Descendants("Node").Where(n => n.Attribute("Text").Value == "SType"),
                n1 => n1.Parent,
                n2 => n2.Parent,
                (n1, n2) => new
                {
                    ParentsValue = n1.Parent.Attribute("Text").Value,
                    PValue = n1.Element("Node").Attribute("Text").Value,
                    SValue = n2.Element("Node").Attribute("Text").Value
                }
            );


var result = Tuples.Where(n => n.PValue == "12" && n.SValue == "1")
                   .Select(n => n.ParentsValue)
                   .ToArray();

关于c# - Linq to XML 通过查询子元素获取父元素属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777231/

相关文章:

c# - 如何使用省略了 lambda 的非常短的 linq 将方法应用于所有列表成员?

c# - Linq 按日期分组(月)

c# - 在 C# 中,有没有一种方法可以使用短前缀而不是每个节点的完整命名空间来生成 XDocument?

vb.net - 将 xdocument 元素(不是元素)作为字符串传递

c# - 为什么我不能写 IO.Directory.GetFiles?

c# - Nhibernate LINQ - 缓存问题

c# - 通用数据库连接 C#

c# - 返回 XDocument 深处的元素值

c# - web.config中如何判断是否编译调试="true"

c# - 来自 wwwroot 的 VS2015 中的引用依赖项