这是一个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);
...
...
}
}
我可以手动删除文本并执行,但我需要在我的代码中解决这个问题以自动清理输入。
答案 0 :(得分:0)
从良好构建的角度来看,文档中存在两个问题。
不允许有两个顶级元素(mts:meta,exchange-documents)。
未声明前缀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>