繁体   English   中英

使用XPATH解析XMl时出现org.xml.sax.SAXParseException

[英]org.xml.sax.SAXParseException while parsing XMl using XPATH

我试图使用XPATH从XML获取值。 我收到以下例外:

    [Fatal Error] books.xml:4:16: The prefix "abc" for element "abc:priority" is not bound.
Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:///D:/XSL%20TEST%20APP%20BACK%20UP/XMLTestApp/books.xml; lineNumber: 4; columnNumber: 16; The prefix "abc" for element "abc:priority" is not bound.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at xpath.XPathExample.main(XPathExample.java:18)

我收到此错误是因为我的XML与正常的XML略有不同(请参见下文):

<?xml version="1.0" encoding="UTF-8"?>
<inventory>
    <Sample>
    <abc:priority>1</abc:priority>  
    <abc:value>2</abc:value>        
    </Sample>
</inventory>

这是我从上面的XML获取值的代码(Java):

import java.io.IOException;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;

    public class XPathExample {

      public static void main(String[] args) 
       throws ParserConfigurationException, SAXException, 
              IOException, XPathExpressionException {

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("books.xml");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr 
         = xpath.compile("//Sample/*/text()");////book/Sample[author='Neal Stephenson']/title/text()

        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue()); 
        }

      }

    }

如果我删除分号,我从来没有得到这个错误。

是否可以使用XPATH从上面提到的XML中获取内容?

是否有可能使用Xpath从上面提到的XML中获取内容? ” - 我不这么认为。 这个XML格式不正确。

从规范( http://www.w3.org/TR/REC-xml-names/#ns-qualnames ):

Prefix提供限定名称的名称空间前缀部分,并且必须与名称空间声明中的名称空间URI引用相关联 [定义:LocalPart提供限定名称的本地部分。]

为了对它做任何事情,我认为你必须添加名称空间声明。

<inventory xmlns:abc="x">
    <Sample>
        <abc:priority>1</abc:priority>  
        <abc:value>2</abc:value>        
    </Sample>
</inventory>

尝试没有这一行:

    domFactory.setNamespaceAware(true); // never forget this!

虽然在没有命名空间感知的情况下运行通常是个坏主意,但在这种特定情况下它是有意义的,因为输入文件就是这样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM