我正在使用java将xml文件转换为字符串 我的xml是
<GTSRequest command="version">
<Authorization account="account" user="user" password="password"/>
</GTSRequest>
和Java代码
public static void main(String[] args) throws IOException {
// TODO code application logic here
String a = System.getProperty("user.dir") + "/XML/Get Current GTS Version.xml";
System.out.println(convertXMLFileToString(a));
}
public static String convertXMLFileToString(String fileName) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(fileName));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
但是当我将XMl转换为String时,我的输出会改变,这是我不想要的。 输出
<?xml version="1.0" encoding="UTF-8" standalone="no"?><GTSRequest command="version">
<Authorization account="account" password="password" user="user"/>
</GTSRequest>
密码和用户按字母顺序更改 我怎么能解决这个问题,谢谢是提前
答案 0 :(得分:1)
您正在将XML转换为文档并在序列化之后......
如果您只想让文件像文本文件那样读取文件:
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}