簡體   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