6

我有一个使用 JDOM 和 xpath 解析 XML 文件的过程来解析文件,如下所示:

private static SAXBuilder   builder         =   null;
private static Document     doc         =   null; 
private static XPath        xpathInstance       =   null;

builder = new SAXBuilder();
Text list = null;

try {
    doc = builder.build(new StringReader(xmldocument));

} catch (JDOMException e) {
            throw new Exception(e);
} 



try {
    xpathInstance = XPath.newInstance("//book[author='Neal Stephenson']/title/text()");
    list = (Text) xpathInstance.selectSingleNode(doc);
} catch (JDOMException e) {
    throw new Exception(e);
}

以上工作正常。xpath 表达式存储在属性文件中,因此可以随时更改。现在我必须处理更多来自遗留系统的 xml 文件,这些文件只会以 4000 字节的块发送 xml 文件。现有处理读取 4000 字节块并将它们存储在 Oracle 数据库中,每个块作为数据库中的一行(对遗留系统进行任何更改或将块存储为数据库中的行的处理是不可能的) .

我可以通过提取与特定 xml 文档相关的所有行并将它们合并,然后使用现有处理(如上所示)来解析 xml 文档,从而构建完整的有效 XML 文档。

但问题是,我需要从 XML 文档中提取的数据将始终位于前 4000 个字节上。这个块当然不是一个有效的 XML 文档,因为它是不完整的,但会包含我需要的所有数据。我不能只解析一个块,因为 JDOM 构建器会拒绝它。

我想知道我是否可以解析格式错误的 XML 块,而不必合并所有部分(可能会达到很多)以获得有效的 XML 文档。这将节省我多次访问数据库来检查一个块是否可用,并且我不必为了能够使用前 4000 个字节而合并 100 个块。

我知道我可能可以使用 java 的字符串函数来提取相关数据,但这可能使用解析器甚至 xpath 吗?还是他们都希望 xml 文档在解析之前是格式良好的文档?

4

1 回答 1

5

您可以尝试使用JSoup来解析无效的 XML。根据定义,XML 应该是格式正确的,否则它是无效的并且不应该被使用。

更新- 示例:

public static void main(String[] args) {
    for (Node node : Parser.parseFragment("<test><author name=\"Vlad\"><book name=\"SO\"/>" ,
            new Element(Tag.valueOf("p"), ""),
            "")) {
        print(node, 0);
    }
}

public static void print(Node node, int offset) {
    for (int i = 0; i < offset; i++) {
        System.out.print(" ");
    }
    System.out.print(node.nodeName());
    for (Attribute attribute: node.attributes()) {
        System.out.print(", ");
        System.out.print(attribute.getKey() + "=" + attribute.getValue());
    }
    System.out.println();
    for (Node child : node.childNodes()) {
        print(child, offset + 4);
    }
}
于 2011-08-08T12:27:39.510 回答