2010-04-20 30 views
3

我需要從其他程序生成的文件刪除非XML標籤。一個簡單的方法來從XML文件刪除頁眉

該文件是一些這樣的:

Executing Command - Blah.exe ... 
-----Command Output----- 
HTTP/1.1 200 OK 
Connection: close 
Content-Type: text/xml 

<?xml version="1.0"?> 
<testResults> 
    <finalCounts> 
    <right>7</right> 
    <wrong>4</wrong> 
    <ignores>0</ignores> 
    <exceptions>0</exceptions> 
    </finalCounts> 
</testResults> 

Exit-Code: 15 

如何輕鬆去除Java中的非XML文本?

回答

8
// getContent() returns the complete text to strip. 
// 
String s = getContent(); 

// Find the start of the XML content using the <?xml prefix. 
// 
int xmlIndex = s.indexOf("<?xml"); 

// Strip the non-XML header. 
// 
s = s.substring(xmlIndex); 

// Find the last closing angle-bracket; should indicate end of the XML. 
// 
xmlIndex = s.lastIndexOf(">"); 

// Strip everything after the closing angle-bracket. 
// 
s = s.substring(0, xmlIndex); 
+0

您可能需要從'xmlIndex'添加或1。減去。 – 2010-04-20 21:19:25

+0

是PHP找這個,但是這有助於弄清楚依然。好工作。 – IamFace 2013-07-12 22:40:19

4

這看起來像直接HTTP輸出...所以只是在掃描前兩個連續的換行符(可能在他們面前的是回車)會給你你想篩選出前綴的結束。

+0

可惜沒有一個'內容Length'頭,可以提供更多的提示。 – McDowell 2010-05-14 18:32:39

相關問題