【发布时间】: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 文档的格式始终正确是一种既定的最佳实践,以避免此类问题。我希望这会有所帮助!