Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

xml - Java XPath: Queries with default namespace xmlns

I want to do an XPath query on this file (excerpt shown):

<?xml version="1.0" encoding="UTF-8"?>
<!-- MetaDataAPI generated on: Friday, May 25, 2007 3:26:31 PM CEST -->
<ModelClass xmlns="http://xml.sap.com/2002/10/metamodel/webdynpro" xmlns:IDX="urn:sap.com:WebDynpro.ModelClass:2.0">
    <ModelClass.Parent>
        <Core.Reference package="com.test.mypackage" name="ModelName" type="Model"/>

This is a snippet of the code I'm using:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document document = builder.parse(new File(testFile));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext( new NamespaceContext() {
    public String getNamespaceURI(String prefix) {
...

String result = xpath.evaluate(xpathQueryString, document);
System.out.println(result);

The problem I'm facing is that when the default namespace is referenced in an XPath query, the getNamespaceURI method is not called to resolve it. This query for example doesn't extract anything:

//xmlns:ModelClass.Parent/xmlns:Core.Reference[@type="Model"]/@package

Now I've tried "tricking" the parser by replacing xmlns with a fake prefix d and then writing the getNamespaceURI method accordingly (so to return http://xml.sap.com/2002/10/metamodel/webdynpro when d is encountered). In this case, the getNamespaceURI is called but the result of the XPath expression evaluation is always an empty string.

If I strip out namespaces from the file and from the XPath query expression, I can get the string I wanted (com.test.mypackage).

Is there a way to make things work properly with the default namespace?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The XPath 1.0 specification requires that "no prefix means no namespace". So JAXP, which was designed for XPath 1.0, is quite right to stop you binding the "null prefix" to some non-null namespace.

XPath 2.0 allows you to declare a default namespace for unqualified names in your XPath expression, but to take advantage of that you will need an API (such as Saxon's s9api) that takes advantage of this feature.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...