用 Java 解析包含 XML 片段的文件 [英] Parse file containing XML Fragments in Java

查看:61
本文介绍了用 Java 解析包含 XML 片段的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个不包含根元素的XML"许可文件,而是包含两个 XML 片段(),所以当我尝试为了解析文件,我(预期)收到了一个关于格式不正确的文档的错误.

I inherited an "XML" license file containing no root element, but rather two XML fragments (<XmlCreated> and <Product>) so when I try to parse the file, I (expectantly) get an error about a document that is not-well-formed.

我需要同时获取 XmlCreatedProduct 标签.

I need to get both the XmlCreated and Product tags.

示例 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 的起点.

Here is the current code that I use to attempt to load the XML. It does not work, but I've used it before as a starting point for well-formed 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) 行,我得到以下异常:

At the db.parse(file) line, I get the following Exception:

[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)

我将如何解析这个令人沮丧的文件?

How would I go about parsing this frustrating file?

推荐答案

如果您知道此文档的格式总是不规范...在 之后添加一个新的虚拟 标签数据.

If you know this document is always going to be non-well formed... make it so. Add a new dummy <root> tag after the <?xml...>and </root> after the last of the data.

这篇关于用 Java 解析包含 XML 片段的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆