【问题标题】:A simple way to remove headers from XML files从 XML 文件中删除标头的简单方法
【发布时间】:2010-04-20 20:12:01
【问题描述】:

我需要从另一个程序生成的文件中删除非 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文本?

【问题讨论】:

    标签: java xml text-processing


    【解决方案1】:
    // 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 );
    

    【讨论】:

    • 您可能需要在xmlIndex 中加或减1。
    【解决方案2】:

    这看起来像是直接的 HTTP 输出...所以只需扫描前两个连续的换行符(可能在它们前面带有回车符)就会给你想要过滤掉的前缀的结尾。

    【讨论】:

    • 可惜没有Content-Length 标头来提供更多提示。
    猜你喜欢
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多