0

I have a xml like below:

<v2:Root xmlns:v2="www.example.com/xsd/">
<ABC>test data</ABC>
<ABC>test data1</ABC>
<ABC>test data2</ABC>
</v2:Root>

When I'm accessing ABC element using JDOM2, i'm getting the element value in debug like

[Element:ABC[Namespace:"www.example.com/xsd/"]].

That's why i couldn't access the element by just using Xpath expression "//ABC". I'm forced to use expression "/*[local-name()='ABC']".Then it works.

Now, my requirement is to acces the elemnt using expression "//ABC" only. Is there any way?

Thanks in advance for any help.

1 Answers1

0

I think you are mistaken about what your XML actually looks like. I believe you also must have:

xmlns="www.example.com/xsd/"

in there somewhere otherwise your ABC Elements would be in the NO_NAMESPACE namespace (and the ABC toString() method would look like: [Element:ABC] )

So, your XML snippet does not match the ABC Element toString() output.

If you fix your question it will be easier to suggest what your XPath expression should look like.


EDIT, assuming I am right that you have the additional redefinition of the default Namespace, then you can use the following JDOM to get the ABC elements:

XPathFactory xpf = XPathFactory.instance();
Namespace defns = Namespace.getNamespace("defns", "www.example.com/xsd/");
XPathExpression<Element> xpe = xpf.compile("//defns:ABC", Filters.element(), null, defns);
List<Element> abcs = xpe.evaluate(doc);

You should read the following exerpt from the XPath specification carefully:

A QName in the node test is expanded into an expanded-name using the namespace declarations from the expression context. This is the same way expansion is done for element type names in start and end-tags except that the default namespace declared with xmlns is not used: if the QName does not have a prefix, then the namespace URI is null (this is the same way attribute names are expanded). It is an error if the QName has a prefix for which there is no namespace declaration in the expression context.

rolfl
  • 17,539
  • 7
  • 42
  • 76