如何使用java将xml文件转换为字符串而不转义XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18472123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert xml file to string without escaping XML using java
提问by Charu Khurana
I've a XML
file and want to send its content to caller as string. This is what I'm using:
我有一个XML
文件,想将其内容作为字符串发送给调用者。这是我正在使用的:
return FileUtils.readFileToString(xmlFile);
return FileUtils.readFileToString(xmlFile);
but this (or that matter all other ways I tried like reading line by line) escapes XML elements and enclose whole XML with <string>
like this
但是这个(或者我尝试过的所有其他方式,比如逐行阅读)会转义 XML 元素并用<string>
这样的方式包围整个 XML
<string>>&lt;.....</string>
<string>>&lt;.....</string>
but I want to return
<a>....</a>
但我想回来
<a>....</a>
回答by stmfunk
I'd advise using a different file reader maybe something like this.
我建议使用不同的文件阅读器,可能是这样的。
private String readFile( String file ) throws IOException {
BufferedReader reader = new BufferedReader( new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
}
It's probably a feature of file utils.
这可能是文件实用程序的一个功能。
回答by Vighanesh Gursale
According to your question you just want to read the file. You can use FileReader
and BufferedReader
to read the file.
根据您的问题,您只想阅读文件。您可以使用FileReader
和BufferedReader
来读取文件。
File f=new File("demo.xml");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!=null)
{
System.out.println(line);
}
Hope this answer helps you
希望这个回答对你有帮助
回答by ccu
IOUtils works well. It's in package org.apache.commons.io. The toString method takes an InputStream as a parameter and returns the contents as a string maintaining format.
IOUtils 运行良好。它位于 org.apache.commons.io 包中。toString 方法将 InputStream 作为参数并以字符串维护格式返回内容。
InputStream is = getClass.getResourceAsStream("foo.xml");
String str = IOUtils.toString(is);
回答by Chinnayya Naidu Nalla
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!= null){
sb.append(line.trim());
}