我继承了一个不包含根元素的“XML”许可证文件,而是包含两个 XML 片段( <XmlCreated>
和 <Product>
),因此当我尝试解析该文件时,我(预期)收到一个有关文档的错误:格式不正确。
我需要同时获取 XmlCreated
和Product
标签。
示例 XML 文件:
<?xml version="1.0"?>
<XmlCreated>May 11 2009</XmlCreated>
<!-- License Key file Attributes -->
<Product image ="LicenseKeyFile">
<!-- MyCompany -->
<Manufacturer ID="7f">
<SerialNumber>21072832521007</SerialNumber>
<ChassisId>72060034465DE1C3</ChassisId>
<RtspMaxUsers>500</RtspMaxUsers>
<MaxChannels>8</MaxChannels>
</Manufacturer>
</Product>
这是我用来尝试加载 XML 的当前代码。它不起作用,但我以前曾使用它作为格式良好的 XML 的起点。
public static void main(String[] args) {
try {
File file = new File("C:\\path\\LicenseFile.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
} catch (Exception e) {
e.printStackTrace();
}
}
在 db.parse(file)
行,我收到以下异常:
[Fatal Error] LicenseFile.xml:6:2: The markup in the document following the root element must be well-formed.
org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at com.mycompany.licensesigning.LicenseSigner.main(LicenseSigner.java:20)
我该如何解析这个令人沮丧的文件?
最佳答案
如果您知道此文档的格式总是不正确...请这样做。添加新的虚拟人 <root>
<?xml...>
之后的标签和</root>
在最后一个数据之后。
关于java - 用Java解析包含XML片段的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3232110/