您仍然可以使用 XPathXDocument
和 LINQ to XML;
var doc = XDocument.Load(filePath);
var myNodeList = doc.XPathSelectElements(".//node[@Attribute1 ='" & varString1 &'']/nodechild[@AttributeChildnode1 = ''& varString2 &'']");
XPathSelectElements
XNode
在命名空间内被声明为扩展方法System.Xml.XPath
。
标准Linq to XML 版本
输入 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
变量值。