I'm having trouble selecting an element with an attribute that ends with a certain value.
XML looks like
<root>
<object name="1_2"><attribute name="show" value="example"></object>
<object name="1_1"><attribute name="show" value="example"></object>
<object name="2_1"><attribute name="show" value="example"></object>
</root>
So I need to extract all values from attributes in objects ends with _1, how can I do that?
I did this code
XmlNodeList childnodes = xRoot.SelectNodes("//Object[@Name='1_1']");
foreach (XmlNode n in childnodes)
Console.WriteLine(n.SelectSingleNode("Attribute[@Name='show']").OuterXml);
but I can't find how to search for the part of attributes name and how to get the exact value of target parameter.
First note that XML and XPath are case sensitive, so Object is different than object, and Name is different than name.
This XPath 2.0 expression,
//object[ends-with(@name,'_1')]
will select all object elements whose name attribute value ends with _1.
XPath 1.0 lacks the ends-with() function but can achieve the same result with a bit more work:
ends-with($s, $e) ≡ (substring($s, string-length($s) - string-length($e) +1) = $e)
Applied to your case where $s is @name and $e is '_1', the above simplifies to this expression:
//object[substring(@name, string-length(@name) - 1) = '_1']
If C# supports XPath 2.0 you should be able to use:
XmlNodeList childnodes = xRoot.SelectNodes("//object[ends-with(@name, '_1')]");
if not then a slightly longer version should work:
XmlNodeList childnodes = xRoot.SelectNodes("//object[substring(@name, string-length(@name) - 1) = '_1']");
Also your xml is not valid as you need to close the attribute elements:
<root>
<object name="1_2"><attribute name="show" value="example"/></object>
<object name="1_1"><attribute name="show" value="example"/></object>
<object name="2_1"><attribute name="show" value="example"/></object>
</root>
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