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>
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!
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']]
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")
);
Given the XML in question, 'item1' and 'item3' elements should be returned by the XPath and the LINQ above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With