/ /複雑なXpathからLinqからXMLへ-xml、linq、linq-to-xml

LinqからXMLへの複雑なXpath - xml、linq、linq-to-xml

私の入力XML:

....
<node Attribute1 = "GUID1">
<childnode1 AttributeChildnode= var1> </childnode>
<childnode2 AttributeChildnode= var2> </childnode>
</node>
<node Attribute1 = "GUID2">
<childnode3 AttributeChildnode= var3> </childnode>
<childnode4 AttributeChildnode= var4> </childnode>
</node>
....

私のXPathコードは次のようになります

mynodelist = xmldoc.SelectNodes(".//node[@Attribute1 ="" & varString1 &""]/nodechild[@AttributeChildnode1 = ""& varString2 &""]")

同じ結果を得るためにLinqtoXMLコードがどのように見えるべきかわかりません 誰か助けてくれませんか

回答:

回答№1は0

XPathは引き続き使用できます XDocument およびLINQto XML;

var doc = XDocument.Load(filePath);
var myNodeList = doc.XPathSelectElements(".//node[@Attribute1 ="" & varString1 &""]/nodechild[@AttributeChildnode1 = ""& varString2 &""]");

XPathSelectElements 上の拡張メソッドとして宣言されています XNode、以内 System.Xml.XPath 名前空間。

標準 LinqからXMLバージョン</ strong>

入力XML:

<root>
<node Attribute1="GUID1">
<childnode AttributeChildNode1="var1" AttributeChildNode2="result1"></childnode>
<childnode AttributeChildNode1="var2" AttributeChildNode2="result2"></childnode>
</node>
<node Attribute1="GUID2">
<childnode AttributeChildNode1="var3" AttributeChildNode2="result3"></childnode>
<childnode AttributeChildNode1="var4" AttributeChildNode2="result4"></childnode>
</node>
</root>

クエリ:

string guid = "GUID1";
string var = "var1";

var elements = XElement.Load("Input.txt");

var value = (from node in elements.Elements("node")
where (string)node.Attribute("Attribute1") == "GUID1"
from childNode in node.Elements()
where (string)childNode.Attribute("AttributeChildNode1") == "var1"
select (string)childNode.Attribute("AttributeChildNode2")).FirstOrDefault();

返品 result1 - result4、 応じて guid そして var 変数値。