简体   繁体   中英

Get all XMLs from raw text file?

I have log file and i need to write programm which get all xml's from this file. File looks like

text
text
xml
text
xml
text 
etc

Can you give me advice what is better to use regexp or something else? Maybe it's possible to do it with dom4j?
If i'll try to use regexp i see next problem that text parts have <> tags.

Update 1: XML example

  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

Thanks.

if your XMl is always on one line then you can just iterate over lines checking if it starts with < . If so try to parse the whole line as 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);
}

Output:

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM