Jackson Ha
Jackson Ha

Reputation: 682

trying to get child of a dynamic element in SimpleXML (Java)

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]

Upvotes: 0

Views: 306

Answers (1)

kjhughes
kjhughes

Reputation: 111686

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]

Upvotes: 1

Related Questions