【问题标题】:Error parsing XML: Content is not allowed in prolog解析 XML 时出错:prolog 中不允许有内容
【发布时间】:2016-11-28 11:03:41
【问题描述】:

这是一个 XML 文档(XML 声明和 XSLT 处理指令之前的句子和空格是输入的一部分):

This XML file does not appear to have any style information associated with it. The document tree is shown below.


    <?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
      <mts:meta name="elapsed-time" value="18" />
      <exchange-documents>
        <exchange-document country="US" number="8049504">
        ....
        ....
        ....

        </exchange-document>
      </exchange-documents>

我正在解析 XML 并使用 XPath。在大多数 XML 文件中,第一行包含一些文本或空格(参考上面的 xml)

如果没有前导文本,它会成功解析,但如果出现任何文本,则会产生以下错误:

--- exec-maven-plugin:1.2.1:exec (default-cli) @ XMLHandling ---

[致命错误] :1:1: prolog 中不允许内容。

我该如何解决这个问题?

我正在使用的代码:

public static void main(String[] args) throws ParseException {

        String filePath = "D:/newxml.xml";

        try {
            FileInputStream file = new FileInputStream(new File(filePath));
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
             Document xmlDocument = builder.parse(file);
            XPath xPath = XPathFactory.newInstance().newXPath();

            String pubOrPatentNumber = xPath.compile("//preference").evaluate(xmlDocument);
            ...
            ...
            }
            }

我可以手动删除文本并执行,但我需要在我的代码中解决这个问题以自动清理输入。

【问题讨论】:

  • 很可能是字节顺序标记。在此处查看可能的解决方案:stackoverflow.com/questions/21891578/…
  • 在代码层面,您可以使用字符串库函数,即查找“”的第一次出现。在包含文档的输入字符串中,然后从此处开始获取子字符串,然后对其进行解析。但是,由于格式正确的错误,我建议谨慎行事。确保 XML 文档的格式始终正确是一种既定的最佳实践,以避免此类问题。我希望这会有所帮助!

标签: java xml xpath


【解决方案1】:

从格式良好的角度来看,文档中有两个问题。

  1. 不允许有两个顶级元素(mts:meta、exchange-documents)。

  2. 前缀 mts 未声明。

这个修改后的文档格式正确(但需要为 mts 调整命名空间 URI,并为包装元素选择适当的名称):

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
<root>
    <mts:meta xmlns:mts="http://www.example.com" name="elapsed-time" value="18" />
    <exchange-documents>
        <exchange-document country="US" number="8049504">
            ....
            ....
            ....
        </exchange-document>
    </exchange-documents>
</root>

【讨论】:

  • Xml 文件来自 http,即我正在动态解析 xml,点击 Url,创建连接等等,每个 Xml 的第一行应该是“这个 XML 文件不似乎有任何与之相关的样式信息。文档树如下所示。”由于第一行,我无法解析文档,也无法更新 xml
  • 感谢您的回复,Prabu,对此深表歉意。我以为这是复制粘贴的人工制品。那么这又是一个问题。此外,如果这是通过 HTTP 检索到的文档,则意味着服务该 XML 的服务器出现问题,除非它应该是 XML 片段,而不是文档。这句话是浏览器显示的吗,因为浏览器在显示 XML 时通常会添加花里胡哨的功能?如果是这样,您可以尝试查看并分享实际的源代码吗?浏览器通常允许您查看原始 XML。
猜你喜欢
  • 2011-06-19
  • 2011-10-23
  • 2023-04-06
  • 2015-11-15
  • 1970-01-01
  • 2011-02-05
  • 2011-03-03
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多