2012-11-26 6 views
1

로그 파일이 있는데이 파일에서 모든 xml을 가져 오는 programm를 작성해야합니다. 파일 당신이 날은 정규 표현식 또는 다른 뭔가를 사용하는 것이 좋습니다 어떤 조언을 줄 수원시 텍스트 파일에서 모든 XML을 가져 옵니까?

text 
text 
xml 
text 
xml 
text 
etc 

처럼 보인다? 아마도 dom4j로 할 수 있을까요?
regexp를 사용하려고하면 텍스트 부분에 <> 태그가있는 다음 문제를 참조하십시오.

업데이트 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 

감사합니다.

+0

^[A-ZA-Z] [A-ZA -0] + [\ n] * $ –

답변

1

, 그것은 매우 간단해야

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

논리는 태그가있는 모든 XML을 가져오고 파일의 다른 텍스트를 잊어 버리는 것입니다. –

+0

내 코드는 XML이 아닌 모든 텍스트를 제거하므로 ...? –

+0

네, 알지만, xml이 별도의 줄에 없다면 어떻게 될까요? –

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> 
관련 문제