[英]Convert XML-File to string without manipulation or optimization in Java
我在使用XML文件时遇到的JDOM2麻烦。 我想将XML文件转换为字符串,而无需任何操作或优化。
多数民众赞成在我的Java代码来做到这一点:
SAXBuilder builder = new SAXBuilder();
File xmlFile = f;
try
{
Document document = (Document) builder.build(xmlFile);
xml = new XMLOutputter().outputString(document);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return xml;
但是,当我将字符串与原始XML文件进行比较时,我注意到了一些更改。
原本的:
<?xml version="1.0" encoding="windows-1252"?>
<xmi:XMI xmi:version="2.1" xmlns:uml="http://schema.omg.org/spec/UML/2.0" xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmlns:thecustomprofile="http://www.sparxsystems.com/profiles/thecustomprofile/1.0" xmlns:SoaML="http://www.sparxsystems.com/profiles/SoaML/1.0">
和字符串:
<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmlns:SoaML="http://www.sparxsystems.com/profiles/SoaML/1.0" xmlns:thecustomprofile="http://www.sparxsystems.com/profiles/thecustomprofile/1.0" xmlns:uml="http://schema.omg.org/spec/UML/2.0" xmi:version="2.1">
并且所有变音符号(ä,ö,ü)也都被更改。 我将得到类似的信息:“ ...”而不是“ä”。
有什么办法可以阻止这种行为?
首先,正如其他人所述,您不应使用任何XML处理。 只需将文件读取为文本文件即可。
其次,由于使用了不正确的字符集(编码),您的变音符号显示为'。'。 字符集错误可能在您的代码中,也可能是XML文件。
原始XML文件包含encoding="windows-1252"
,但是将XML编码为除UTF-8之外的其他格式是不寻常的,因此我怀疑该文件确实是UTF-8文件,并且声称使用的编码不是正确。
读取文件时,尝试强制使用UTF-8。 无论如何,在将字节转换为文本时指定字符集都是一个好习惯:
String xml = new String(
Files.readAllBytes(xmlFile.toPath()), StandardCharsets.UTF_8);
看看这是否适合您。
//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());
}
尝试这个 :
String xmlToString=FileUtils.readFileToString(new File("/file/path/file.xml"));
您需要为此准备Commons-io jar。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.