具有通配符属性名称和特定属性值的C#和XPath [英] C# and XPath with wildcard attribute name and specific attribute value

查看:67
本文介绍了具有通配符属性名称和特定属性值的C#和XPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用XPath查找具有其名称以一组特定字符开头且该属性的值包含特定值的属性的所有元素吗?例如:

Can I use XPath to find all elements that have an attribute whose name begins with a certain set of characters and the value of the attribute contains a certain value? For example:

<items>
     <item id="item1" attr-name0="UPC" attr-value0="12345" attr-name1="Price" attr-value1="10.00" attr-name2="Enabled" attr-value2="true"/>
     <item id="item2" attr-name0="Price" attr-value0="25.00" attr-name1="Enabled" attr-value1="false"/>
     <item id="item3" attr-name0="Price" attr-value0="10.00" attr-name1="UPC" attr-value1="54321" attr2-name="UPC" attr-value2="abcde"/>
</items>

最终,我需要找到已指定一个或多个UPC的商品的ID和UPC.最多有11个属性(attr-name0到attr-name10).我可以使用C#和XML(XPath)/LINQ来完成此任务.谢谢!

Ultimately I need to find the id and UPCs for the items that have one or more UPCs specified. There are a maximum of 11 attributes (attr-name0 to attr-name10). I can use C# and XML(XPath)/LINQ to accomplish this. Thank you!

推荐答案

以下XPath应该返回<item>元素,其中以"attr-name"开头的属性之一的值为"UPC":

The following XPath should return <item> elements where one of attribute that starts with 'attr-name' has value of 'UPC' :

//item[@*[starts-with(name(), 'attr-name') and .='UPC']]

等效的LINQ-to-XML看起来像这样(假设docXDocumentXElement的实例):

The equivalent LINQ-to-XML would look about like this (assume doc is an instance of XDocument or XElement) :

doc.Descendants("item")
   .Where(i => i.Attributes()
                .Any(a => a.Name.ToString().StartsWith("attr-name") && a.Value == "UPC")
    );

鉴于有问题的XML,"X3"和上面的LINQ应该返回"item1"和"item3"元素.

Given the XML in question, 'item1' and 'item3' elements should be returned by the XPath and the LINQ above.

这篇关于具有通配符属性名称和特定属性值的C#和XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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