【问题标题】:Parse out XML from "unstructured" plain text从“非结构化”纯文本中解析出 XML
【发布时间】:2015-02-03 16:11:05
【问题描述】:

我正在使用来自发布系统的大型文本文件。其结构如下:

-- File header
-- File Attribute 1
-- File Attribute 2

<xml>File summary</xml>

-- Record header
-- Record attribute 1

<xml>Record1</xml>

-- Record 1 header
-- Record attribute 1

<xml>Record1</xml>

-- Record 2 header
-- Record attribute 1

<xml>Record2</xml>

-- Record n header
-- Record attribute 1

<xml>Recordn</xml>

一个文件中可能有数十万条记录,并且 XML 是一个大型结构一行。行大小可以达到数千个字符。

首先,是的,这太疯狂了——我的第一个任务是回到发布系统并解释 XML 的工作原理! ;) 同时,我需要一种剥离 XML 并构建结构化输出文件的方法:

<xml>
    <header/>
    <listofrecords>
        <record1/>
        <record2/>
        <recordn/>
    </listofrecords>
</xml>

请注意,我对文本标题内容的内容不感兴趣。

我正在努力寻找最快、最易于维护的方法。

我的想法是使用 Java 和 BufferedReader 逐行解析输入文件。在遇到 XML 标记的地方,我读取结束 XML 标记并添加到输出文件结构中。

有没有更快的方法来做到这一点? RegEx 能否帮助识别我需要提取为新格式的文本?

很抱歉,这是一个非常开放的问题,如果它不在 Stack Overflow 的范围内,我会理解的。任何想法都非常感谢,虽然

【问题讨论】:

  • 我认为您需要删除正则表达式标签..
  • 完成,抱歉。我只是想知道 RegEx 是否会提供一种快速的方法来识别文件中的 XML 行。

标签: java xml


【解决方案1】:

我会使用 perl 脚本

#! /usr/bin/perl
#
print "<xml>\n";
while($line = <>) {
    if ($line =~ m!-- File (.*)!) {
        print "    <header $1/>\n";
        print "    <listofrecords>\n";
        last;
    }
}
while($line = <>) {
    if($line =~ m!<xml>(.*)</xml!) {
        print "        <$1/>\n";
    }
}
print "    </listofrecords>\n";
print "</xml>";

【讨论】:

  • 是的,perl 是要走的路。
  • 非常好 - 非常感谢您!我写了几十行 Java 来做同样的事情。在 Perl 中更整洁。
【解决方案2】:

您可以考虑使用 DOM 解析器。如果您正在处理这样一个大文件,请用一些标记将其包围以使其成为有效的 XML,例如

    <top>
        ...file contents...
    </top>


String xmlPath = "C:/test/xml/publishing_file.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(xmlPath);

    NodeList nl = dom.getDocumentElement().getChildNodes();
    for(int i = 0; i < nl.getLength(); i++){
        //...this sequence of nodes will be each <xml> tag followed by the text contents between it
    }

比解析每一行要容易一点...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    相关资源
    最近更新 更多