XML中的空格

时间:2013-02-14 00:47:58

标签: java xml xpath

我正在尝试使用SBA api中的xml文件。

  

http://api.sba.gov/loans_grants/federal_and_state_financing_for/ny.xml

问题是当我尝试使用xpath解析此xml时出现此错误:

  

[致命错误] loans_grants.dtd:3:22:之前需要空格   元素属性“CDATA”声明中的属性类型   “计数”。线程“main”org.xml.sax.SAXParseException中的异常:   声明中的属性类型之前需要空格   元素“count”的属性“CDATA”。

在观察xml文件后,我认为问题出现在以下行和类似的行之后:

<grant_loans count="103">

<industry nil="true"/>

<state_name nil="true"/>

我认为如果count"103"以及nil"true"之间存在空格,则不会发生此错误。由于整个xml太大,我复制了它的一部分并进行了这些更改并保存在我的本地存储中。然后我可以运行并正确解析它。我只是放了一些像这样的空格:

<grant_loans count = "103">

如何将我的程序用于需要空间的所有地方,然后将其用于进一步解析?

如果你需要,我可以在这里发布我的java代码但是该代码适用于其他xml文件,所以我认为这个xml文件存在问题。

修改

Java代码段:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    Document doc = null;
    XPathExpression expr = null;
    builder = factory.newDocumentBuilder();
    doc = (Document) builder
            .parse("http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway&sensor=false");

    // Create a XPathFactory
    XPathFactory xFactory = XPathFactory.newInstance();

    // Create a XPath object
    XPath xpath = xFactory.newXPath();

    // Compile the XPath expression
    expr = xpath.compile("//geometry/location/lat/text()");
    System.out.println("expr" + expr);
    // Run the query and get a nodeset
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    // Cast the result to a DOM NodeList
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue());  
    }

                       //this works
// 
// some other code
//
builder = factory.newDocumentBuilder();
    url = "http://api.sba.gov/loans_grants/federal_and_state_financing_for/ny.xml";
    doc = builder.parse(url); // problem occurs here
    xFactory = XPathFactory.newInstance();

    // Create a XPath object
    xpath = xFactory.newXPath();

    // Compile the XPath expression
    expr = xpath.compile("//grant_loan/url/text()");
    result = expr.evaluate(doc, XPathConstants.NODESET);

    // Cast the result to a DOM NodeList
    nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue());
    }

//other stuffs

1 个答案:

答案 0 :(得分:1)

这不是XML。它告诉你the DTD被抬高了。请注意错误开头的loans_grants.dtd:3:22。它指向第3行:

<!ATTLIST count CDATA>

应该改为阅读

<!ATTLIST grant_loans count CDATA #REQUIRED>

错误指出ATTLIST的{​​{3}}是:

<!ATTLIST element-name attribute-name attribute-type default-value>

它在第三个位置看到字符串“CDATA”,假设它是属性名称,并且仍然期望获得属性类型,但是它找到了ATTLIST的结尾。这就是为什么它给出了关于期望空白空间的潜在混淆信息。

最有可能的是,当您复制某些xml以在本地运行时,您就会停止DTD声明,这也可以解决问题。

相关问题