0

First, I am new in Xpath. I have found plenty of samples that queries if an element exists ,using Xpath. But I could not manage to implement the sample that I want. My xml is like:

<a>
    <b>
        <c>xxx</c>
        <d>yyy</d>
    </b>
</a>
<a>
    <b>
        <d>zzz</d>
    </b>
</a>

And I only want the "a" items with both "c" and "d" exists. So I did this:

@XPath("a/b[boolean(c) and boolean(d)]")
private A a;

COuld someone please show me the right way to do it?

Thanks

Ali

Neron
  • 1,500
  • 7
  • 30
  • 52

1 Answers1

1
a[descendant::c and descendant::d]

selects a nodes with descendant nodes c and d.

Note that your XML sample is invalid as it lacks a root node (presumably it is just a sample, not your actual document...).

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
  • Thanks for the answer. Actually I think it should be like this: a/b[//c and //b] . I have tried your way and mine but it still jaxb still gives all the "a" elements :( – Neron Oct 12 '14 at 10:47
  • it depends on how specific you want to be. You're specifying `c` and `d` nodes under `a/b` with your original query--your question only says that you want `a` nodes where both `c` and `d` are descendants. Your query in the comment won't work because `//` searches for any node under the root node--you want nodes that are descendants of `a`. If you have a specific output in mind, you need to state it clearly in your question. – i alarmed alien Oct 12 '14 at 11:02
  • u are right about the "a under b and c" thing and I have corrected it :) thx. I have used descendant but it brings no elements even there are suitable ones :( I do not know if it is because of the annotation – Neron Oct 12 '14 at 11:07
  • 1
    Does your XML validate? Have you tried the xpath using an online tester (e.g. http://www.freeformatter.com/xpath-tester.html) and your actual XML? There are a number of possible problems if the XPath isn't working -- it might be nothing to do with the XPath itself. :\ – i alarmed alien Oct 12 '14 at 11:11
  • 2
    As one tag of the OP mentions that moxy is used, axes like descendant:: etc won't work. See e.g. here: http://stackoverflow.com/questions/8404134/eclipselink-moxy-xmlpath-support-for-axes-parent and the still not resolved bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=365840 – matthias_h Oct 12 '14 at 11:25
  • @matthias_h I haven't used moxy, but I suspected that might be why this wasn't working... – i alarmed alien Oct 12 '14 at 11:27
  • matthias_h I think that is my answer, thx my friends, thx @i-alarmed-alien – Neron Oct 12 '14 at 11:35
  • @Neron *maybe* XPath that doesn't contain axis will work in moxy : `a[b[c and d]]` – har07 Oct 12 '14 at 12:30