Search code examples
xmlxpathheaderelementstartswith

How to get an element which starts with a pattern from XML array using xpath 1.0?


The following XML:

<Headers>
    <string>Date:Fri, 12 Feb 2016 13:37:00 GMT</string>
    <string>Location:https://abc/1</string>
</Headers>

How to get the value from the location header (e.g. https://abc/1)?

I've tried XPath 1.0 below without result.

//Headers[starts-with(/string,'Location:')]

Solution

  • Remove the leading / from /string, or add a . before it :

    //Headers[starts-with(string,'Location:')]
    

    That will make the expression relative to current Headers context. Otherwise it means root element string, which, I believe, is not what you actually want.

    Another problem is, that starts-with() expects singular value as parameter. When Headers has multiple string child, only the first string will be evaluated. You can use the following expression to fix it :

    //Headers[string[starts-with(.,'Location:')]]
    

    UPDATE :

    To return portion of the text after "Location:", you can use substring-after() :

    substring-after(//Headers/string[starts-with(.,'Location:')],'Location:')