Java:将格式化的xml文件转换为一个行字符串

Ian*_*the 22 java xml string

我有一个格式化的XML文件,我想将它转换为一个行字符串,我该怎么做.

示例xml:

<?xml version="1.0" encoding="UTF-8"?>
<books>
   <book>
       <title>Basic XML</title>
       <price>100</price>
       <qty>5</qty>
   </book>
   <book>
     <title>Basic Java</title>
     <price>200</price>
     <qty>15</qty>
   </book>
</books>
Run Code Online (Sandbox Code Playgroud)

预期产出

<?xml version="1.0" encoding="UTF-8"?><books><book> <title>Basic XML</title><price>100</price><qty>5</qty></book><book><title>Basic Java</title><price>200</price><qty>15</qty></book></books>
Run Code Online (Sandbox Code Playgroud)

提前致谢.

ant*_*ant 44

//filename is filepath string
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();

while((line=br.readLine())!= null){
    sb.append(line.trim());
}
Run Code Online (Sandbox Code Playgroud)

使用StringBuilder比concat http://kaioa.com/node/59更有效


Mad*_*sen 7

使用和运行XSLT 标识转换<xsl:output indent="no"><xsl:strip-space elements="*"/>

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" />
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

它将删除任何非重要的空格并生成您发布的预期输出.


luk*_*ymo 6

// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t": 
s.replaceAll("\n",""); 
s.replaceAll("\t","");
Run Code Online (Sandbox Code Playgroud)

编辑:

我犯了一个小错误,最好在你的情况下使用StringBuilder(我想你不需要线程安全的StringBuffer)

  • 如果内容元素之间有空格,例如<text> foo(换行符)栏</ text>,该怎么办? (3认同)

小智 5

在 java 1.8 及以上

BufferedReader br = new BufferedReader(new FileReader(filePath));
String content = br.lines().collect(Collectors.joining("\n"));
Run Code Online (Sandbox Code Playgroud)