【问题标题】:Wrong xml format: white space error错误的 xml 格式:空格错误
【发布时间】:2012-12-13 16:41:29
【问题描述】:

对于提出同样的问题,我深表歉意,但根据我的研究,这似乎是在不同的背景下。我知道为什么会出现错误,但我没有查看和关注一些编程论坛就无法根除它。我的程序如下:我正在 ping 一个 url 并打开输入流,然后将该流写入一个 xml 文件。之后,我使用 Xpath 提取一些信息,这些信息将进一步用于某些计算。我的代码如下:

    URL u=new URL("url here");
    HttpURLConnection con=(HttpURLConnection)u.openConnection();
    InputStream is=con.getInputStream();
    BufferedInputStream br=new BufferedInputStream(is);

    File f=new File("data.xml");
    if(f.exists())f.delete();
    f.createNewFile();
    byte data[] = new byte[1024];
    int count;
    FileOutputStream fout = new FileOutputStream(f);
    while((count = br.read(data,0,1024)) != -1)
    {
            fout.write(data, 0, count);
    }
    fout.close();

    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db=dbf.newDocumentBuilder();
    Document doc=db.parse("data.xml");

    XPathFactory  factory=XPathFactory.newInstance();
    XPath xPath=factory.newXPath();
    XPathExpression expr = xPath.compile("//tr/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());
    }

执行此代码时,我得到:publicId 和 systemId 之间需要空格。 由于我是直接写入文件,哪里可能会出现这个空白错误?

【问题讨论】:

  • 可以给我们看看data.xml的内容吗?
  • 正如burna 在他的answer 中所说。您可以使用JSoup 来解析HTML 文件。
  • 好的,谢谢,我现在正在使用 JSoup,但您能否告诉我发生此空白错误的可能原因,因为我只是将整个页面标签复制到文档中。它是在我复制文件时发生的,还是由于我正在处理 HTML 文件和 XML 之类的事实?谢谢。

标签: java xml inputstream


【解决方案1】:

您之前编写的 XML 文件似乎无效,这就是您在解析文件时遇到错误的原因。标准 XML 解析框架只接受格式良好的有效 XML。

如果您想使用无效的、可能不平衡的 HTML 标记汤,我推荐 JSoup,因为它可以使用无效的 XML。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 2011-10-10
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多