C# 使用LINQ选择基于子体的XML事务
我想获得一个基于子代的事务列表。但是我在获取正确的linq语法时遇到了困难。 我的数据如下所示:C# 使用LINQ选择基于子体的XML事务,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我想获得一个基于子代的事务列表。但是我在获取正确的linq语法时遇到了困难。 我的数据如下所示: <Data> <MyTransactionXML> <contract> <contractID>1234</contractID> <ProductCode>ABC</ProductCode> <
<Data>
<MyTransactionXML>
<contract>
<contractID>1234</contractID>
<ProductCode>ABC</ProductCode>
</contract>
...
</MyTransactionXML>
<MyTransactionXML>
<contract>
<contractID>13334</contractID>
<ProductCode>DEF</ProductCode>
</contract>
...
</MyTransactionXML>
</Data>
我不想硬编码它是MyTransactionXML.contract.ProductCode,因为如果位置发生变化,或者我们使用类似的交易和产品代码,但结构不同,我仍然希望能够获得交易。您应该使用Any()
而不是Where()
按产品代码筛选事务时,因为谓词应返回布尔值
from t in xdoc.Descendants("MyTransactionXML")
where t.Descendants("ProductCode").Any(c => (string)c == "DEF") // here
select t
与lambda语法相同:
xdoc.Descendants("MyTransactionXML")
.Where(t => t.Descendants("ProductCode").Any(c => (string)c == "DEF"))
或者可以使用XPath扩展
xdoc.XPathSelectElements("//MyTransactionXML[*/ProductCode='DEF']");
*
通配符匹配任何节点,因此您将处理xml结构的更改在按产品代码筛选事务时,应使用any()
而不是Where()
,因为谓词应返回布尔值
from t in xdoc.Descendants("MyTransactionXML")
where t.Descendants("ProductCode").Any(c => (string)c == "DEF") // here
select t
与lambda语法相同:
xdoc.Descendants("MyTransactionXML")
.Where(t => t.Descendants("ProductCode").Any(c => (string)c == "DEF"))
或者可以使用XPath扩展
xdoc.XPathSelectElements("//MyTransactionXML[*/ProductCode='DEF']");
*
通配符匹配任何节点,因此您将处理xml结构的更改那么您到底想做什么-1如我的问题中所述,如何选择指定的事务。那么您到底想做什么-1就像我的问题中所说的,我如何选择指定的事务。很酷,我使用了第一种方法,它成功了。谢谢你的第二条路!很酷,我使用了第一种方法,效果很好。谢谢你的第二条路!