繁体   English   中英

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

[英]Linq to XML Get parent element attribute value by querying it's children

我正在尝试构建一个Linq to XML Query但尚未找到真正的解决方案。

这是我的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();

处理XML XPath是你的朋友......

对于PType 12,Stype 1

var result = xml.XPathSelectElements(@"//Node[Node[@Value='PType']/Node[@Value='12'] and Node[@Value='SType']/Node[@Value='1']]");

那有点拗口......

//Node

树中任何位置的每个节点

[Node[@Value='PType']

它有一个Node类型的子节点,其属性Value具有值(!)PType

/Node[@Value='12']

它有一个Node类型的子节点,其Value属性值为12

而且所有的东西去S型1

您可以使用XPath过滤掉XML,它可以让您搜索与模式匹配的后代 - 它的适应性。

因此,如果你用string.format替换上面的字符串,那么你就会离开并运行......

暂无
暂无

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

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