1

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();
}
4

2 に答える 2

2
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();
于 2012-03-19T20:56:41.670 に答える
2

XML を扱う場合、XPath はあなたの味方です...

Pタイプ12、Sタイプ1用

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

それはちょっと一口です…。

//Node

ツリー内のすべてのノード

[Node[@Value='PType']

これには、値 (!) PType を持つ属性 Value を持つタイプ Node の子ノードがあります。

/Node[@Value='12']

値が 12 の Value 属性を持つタイプ Node の子ノードを持つ

また SType 1 に到達するためのすべてのもの

XPath を使用して XML を完全にフィルター処理することができ、パターンに一致する子孫を検索できます。

したがって、上記の文字列を string.format に置き換えると、離れて実行されます...

于 2012-03-19T21:42:38.993 に答える