0

I'm trying to access the value of the productType element using Simple Framework XML. However, the catch is that the parent element of that could be anything (ie abc1, abc2). I have seen some examples where it could be done with ElementUnion. However, those implementations require you to know the node value upfront. I was hoping to do it without knowing that.

It seems like SimpleXML doesn't support all the standard XPath features, so despite the below XPATH being valid, SimpleXML doesn't seem to like it. Any suggestions?

sample 1:
<?xml version="1.0" encoding="utf-8"?>
  <t1>
    <t11></t11>
    <abc1>
      <productType>APPLE</productType>
    </abc1>
  </t1>

sample 2:
<?xml version="1.0" encoding="utf-8"?>
  <t1>
    <t11></t11>
    <abc2>
      <productType>ORANGE</productType>
    </abc2>
  </t1>

Valid XPath, but SimpleXML does not like it:

/t1/*//productType[1]
Jackson Ha
  • 662
  • 2
  • 7
  • 13

1 Answers1

1

You don't show what error SimpleXML gives, but your trouble may well be related to XPath in general.

You're right to use * to match any element. However...

NOTE: The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.

So, if you want the first of all productType elements found under any of your varying abc parent elements (beneath t1), use this XPath instead:

(/t1/*/productType)[1]
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Hi kjhudges, thanks for your reply.. when I run your suggested xpath... i am getting the following: org.simpleframework.xml.core.PathException: Illegal character '(' in element for '(/t1/*/productType)[1]' in field 'productType' private java.lang.String com. .... Info.productType – Jackson Ha Jan 02 '15 at 19:48
  • I'd switch to a compliant XPath processor. If that's not possible, as a work-around, you can use `/t1/*/productType` to select a list of `productType` elements, and then use Java to select the first element in the list. – kjhughes Jan 02 '15 at 20:01
  • 1
    That's perfectly legal XPath - but SimpleXML is known to cause a [lot](http://stackoverflow.com/questions/12648363/xpath-simplexml-selection-of-child-based-on-value-of-childs-sibling) of [trouble](http://stackoverflow.com/questions/12298673/how-do-i-use-the-value-of-an-xml-element-when-setting-the-path-in-the-java-simpl?lq=1). Everybody looks for another library or writes their own. – Mathias Müller Jan 02 '15 at 21:13