如何基于子元素名称和值查找XmlNodes [英] How to find XmlNodes based on a child elements name and value

查看:61
本文介绍了如何基于子元素名称和值查找XmlNodes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获取XmlNodeList,其中有1个孩子的特定名称为

Im having trouble getting a XmlNodeList where there is 1 child with a specific name that

<tables>
  <table tableName="Orders">
    <item table="Orders">
      ...
   </item>
    <item table="Orders">
      ...
   </item>
  </table>
  <table tableName="OrderWithParent">
    <item table="OrderWithParent">
      <column columnName="OrderWithParentId"><![CDATA[156]]></column>
      <column columnName="OrderParentId"><![CDATA[1]]></column>
      ...
   </item>
    <item table="OrderWithParent">
      <column columnName="OrderWithParentId"><![CDATA[156]]></column>
      <column columnName="OrderParentId"><![CDATA[1]]></column>
      ...
   </item>
    <item table="OrderWithParent">
      <column columnName="OrderWithParentId"><![CDATA[156]]></column>
      <column columnName="OrderParentId"><![CDATA[2]]></column>
      ...
   </item>
  </table>
</tables>

这就是我的基本xml布局...

So thats my basic xml layout...

我已经反序列化了最重要的Orders ...,现在我想找到OrderWithParent所在的列,它们的列为columnName ="OrderParentId" == order.Id

Ive deserialized the top Orders... and now i wanna find the OrderWithParent's where their column with columnName="OrderParentId" == order.Id

按以下方式检索订单节点:

the order nodes where retrieved like this:

var orders = root.SelectNodes("/tables/table[@tableName='Orders']/item[@table='Orders']");

所以atm即时通讯使用的是XmlDocument ..即时通讯也希望也使用XDocument ..,但是我还无法找到其中一个的解决方案.非常感谢您的帮助!

So atm im using an XmlDocument.. im hope to using XDocument aswell.. but i havent been able to find a solution with either of them. Help is much appreciated!

推荐答案

假定order.Id表示未显示的预定义变量orderId属性,则以下XPath应该返回目标元素:

Assuming that order.Id means Id property of a predefined variable order which you didn't show, the following XPath should return the target item element :

var xpath = $"//item[@table='OrderWithParent' and column[@columnName='OrderWithParentId'] = {order.Id}]";

对于不支持字符串插值$的旧C#版本:

For older C# version where string interpolation $ is not supported :

var xpath = String.Format("//item[@table='OrderWithParent' and column[@columnName='OrderWithParentId'] = {0}]", order.Id);

另一个假设是,order.Id值始终是数字.否则,您需要在XPath中用引号将值引起来,即上述代码段中,将{order.Id}替换为'{order.Id}'或将{0}替换为'{0}'.

Another assumption is, that order.Id value is always number. Otherwise you'll need to wrap the value with quotes in the XPath i.e in the above snippet, replace {order.Id} with '{order.Id}' or {0} with '{0}'.

如果您切换为使用XDocument,则仍可以通过 XPathSelectElement()

If you switch to using XDocument, you can still execute the same XPath expression through XPathSelectElements(), XPathSelectElement(), or XPathEvaluate() methods.

这篇关于如何基于子元素名称和值查找XmlNodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆