imbeginner
imbeginner

Reputation: 411

XPath using starts-with function

I'm writing Java on Android to retrieve data from XML file, but I've got a problem. Consider this XML:

<ITEM>
   <REVENUE_YEAR>2554-02</REVENUE_YEAR>
   <REGION>Central</REGION>
</ITEM>
<ITEM>
  <REVENUE_YEAR>2552-02</REVENUE_YEAR>
  <REGION>Central</REGION>
</ITEM>
<ITEM>
  <REVENUE_YEAR>2552-03</REVENUE_YEAR>
  <REGION>Central</REGION>
</ITEM>

How can I get all elements in years that start-with 2552. I tried:

//REVENUE_YEAR[starts-with(.,'2552')]/text()

It works, but when I tried:

//REVENUE_YEAR[starts-with(.,'2552')]/REGION/text() 

it doesn't work.

Upvotes: 39

Views: 124280

Answers (3)

Vishal
Vishal

Reputation: 61

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

Upvotes: 6

Divyesh Patel
Divyesh Patel

Reputation: 1147

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

Upvotes: 6

user357812
user357812

Reputation:

Use:

/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION

Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with // operator when the schema is well known.

Upvotes: 54

Related Questions