从原始文本文件中获取所有XML?

时间:2012-11-26 13:00:00

标签: java xml regex parsing

我有日志文件,我需要编写programm,从这个文件中获取所有xml。 文件看起来像

text
text
xml
text
xml
text 
etc

你能给我一些建议什么是更好的使用正则表达式或其他东西? 也许用dom4j可以做到这一点? 如果我将尝试使用正则表达式,我会看到下一个问题,即文本部分有<>个标记。

更新1: XML示例

  SOAP message:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
 here is body part of valid xml
</soapenv:Body>
</soapenv:Envelope>
text,text,text,text
symbols etc
  SOAP message:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
 here is body part of valid xml
</soapenv:Body>
</soapenv:Envelope>
text,text,text,text
symbols etc

感谢。

2 个答案:

答案 0 :(得分:1)

如果您的XMl总是在一行上,那么您可以迭代检查它是否以<开头。如果是这样,尝试将整行解析为DOM。

String xml = "hello\n" + //
        "this is some text\n" + //
        "<foo>I am XML</foo>\n" + //
        "<bar>me too!</bar>\n" + //
        "foo is bar\n" + //
        "<this is not valid XML\n" + //
        "<foo><bar>so am I</bar></foo>\n";
List<Document> docs = new ArrayList<Document>(); // the documents we can find
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
for (String line : xml.split("\n")) {
    if (line.startsWith("<")) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(line.getBytes());
            Document doc = docBuilder.parse(bis);
            docs.add(doc);
        } catch (Exception e) {
            System.out.println("Problem parsing line: `" + line + "` as XML");
        }
    } else {
        System.out.println("Discarding line: `" + line + "`");
    }
}
System.out.println("\nFound " + docs.size() + " XML documents.");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
for (Document doc : docs) {
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(sw));
    String docAsXml = sw.getBuffer().toString().replaceAll("</?description>", "");
    System.out.println(docAsXml);
}

输出:

Discarding line: `hello`
Discarding line: `this is some text`
Discarding line: `foo is bar`
Problem parsing line: `<this is not valid XML` as XML

Found 3 XML documents.
<foo>I am XML</foo>
<bar>me too!</bar>
<foo><bar>so am I</bar></foo>

答案 1 :(得分:1)

如果每个这样的部分都在单独的行中,那么它应该非常简单:

s = s.replaceAll("(?m)^\\s*[^<].*\\n?", "");