Xpath expression to find values that start with
Asked Answered
G

2

41

I need an Xpath expression that will select values that start with a certain value. For this instance I am using the id field.

@id=[starts-with(name(),'value')

The following does not work. Is there a way to use the starts-with command with the value between the tags? Or is there another means in Xpath of selecting a matching a value with a known value.

Here is a sample of the XML I am trying to drill into:

<bean>
    <id>AnnotationsBasedJMXAutoExporter</id>
    <class>org.springframework.jmx.export.MBeanExporter</class>
    <lazy-init>false</lazy-init>
    <property>assembler
        <!-- will create management interface using annotation metadata -->
        <bean></bean>
    </property>
</bean>
Godthaab answered 17/5, 2013 at 10:31 Comment(2)
What XML should be matched by this?Tutu
@choroba wouldn't this just match to the attribute tags rather than the value within the tags? I am after the value within the tags. Not the tag nameGodthaab
G
71

I think this xpath should work //id[starts-with(text(),'Annotations')]

Georganngeorge answered 17/5, 2013 at 11:36 Comment(1)
+1, though I'd recommend using . rather than text(), i.e. //id[starts-with(., 'whatever')]. As a general rule you should avoid using text() in XPath expressions unless you are really sure that you need it. Remember that it means "the set of all text node children of ..." (or "the first text node child of ..." if you're treating it as a string), which is not necessarily the same as "the text value of ..."Beebeebe
B
0

Allow me to replace your id tagname with div for these examples, to avoid confusion with attribute id.

First way:

//div[starts-with(text(), 'Annotations')]:

This XPath expression selects <div> elements that have an immediate child text node that starts-with 'Annotations`.

Second Way:

//div[starts-with(., 'Annotations')]:

This XPath expression selects <div> elements whose string value is starts-with 'Annotations`.

For detailed explanation about the difference between these two ways

Burl answered 8/2 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.