gpt4 book ai didi

具有通配符属性名称和特定属性值的 C# 和 XPath

转载 作者:数据小太阳 更新时间:2023-10-29 02:39:23 26 4
gpt4 key购买 nike

我能否使用 XPath 查找具有名称以特定字符集开头且属性值包含特定值的属性的所有元素?例如:

<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 来完成这个。谢谢!

最佳答案

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

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

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

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

鉴于所讨论的 XML,“item1”和“item3”元素应该由上面的 XPath 和 LINQ 返回。

关于具有通配符属性名称和特定属性值的 C# 和 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37703741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com