问题
I'm using SimpleXML (Java) and I'm trying to get a List of objects based on the value of one of the siblings of the list.
So, here's my XML:
<xml>
<metadata>
<resources>
<resource>
<ittype>Service_Links</ittype>
<links>
<link>
<path>http://www.stackoverflow.com</path>
<description>Stack Overflow</description>
</link>
<link>
<path>http://www.google.com</path>
<description>Google</description>
</link>
</links>
</resource>
<resource>
<ittype>Article_Links</ittype>
<links>
...
</links>
</resource>
...
</resources>
</metadata>
</xml>
What I am trying to do is create a SimpleXML-annotation using XPath in order to get a List of all of the "links" where the list's sibling "ittype" equals "Service_Links".
So, for example, this works but only if I'm trying to statically get the 1st "resource"-node (as opposed to dynamically getting the "resource"-node based on what it's sibling "ittype" is:
@ElementList(name="links")
@Path("metadata/resources[1]/resource")
public List<Link> link;
I've tried so many ways to format the xpath to dynamically find the "resource"-node I want that I couldn't possibly list them all here; however, this is one example I've tried that seems to me it should work; no clue what I'm doing wrong...
@ElementList(name="links")
@Path("metadata/resources[resource/ittype='Service_Links']/resource")
public List<Link> link;
I've googled a ton, including here on SO, and just can't find much very similar; and what I did find, didn't translate well enough for me to spot what I need to do. For example, this SO didn't seem to work even though it's pretty similar.
UPDATE #1 (8OCT @ 12:38pm)
Per feedback, I have tried this:
@ElementList
@Path("metadata/resources/resource[ittype='Service_Links']")
public List<Link> link;
No dice: org.simpleframework.xml.core.PathException: Invalid index for path 'metadata/resources/resource[ittype='Service_Links']' in field 'links'
回答1:
I never got SimpleXml to implement this style of XPath; from reading through their docs more thoroughly, it looks like they haven't implemented this XPath feature yet.
So I settled on a different XML-parsing strategy here: https://stackoverflow.com/a/13236117/483257
回答2:
I don't know about SimpleXML specifically, but this xpath should get you the elements you want:
metadata/resources/resource[ittype = 'Service_Links']
回答3:
- Your xml example is not well-formed. The
link
element doesn't have its closing counterpart. The same applies for thedescription
el. I assume these are just typos. - Here is the working XPath expression:
/metadata/resources/resource/links/link[parent::links/preceding-sibling::ittype/text()=='Service_Links']
or much simpler version:
/metadata/resources/resource[ittype = 'Service_Links']/links/link
来源:https://stackoverflow.com/questions/12648363/xpath-simplexml-selection-of-child-based-on-value-of-childs-sibling