Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath for attribute value that ends with a string?

Tags:

c#

xml

xpath

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.

like image 298
tehdima Avatar asked Oct 23 '25 12:10

tehdima


2 Answers

First note that XML and XPath are case sensitive, so Object is different than object, and Name is different than name.

XPath 2.0

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

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']
like image 92
kjhughes Avatar answered Oct 25 '25 01:10

kjhughes


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>
like image 34
Jan-Peter Vos Avatar answered Oct 25 '25 01:10

Jan-Peter Vos