1
我有一個包含中文內容的XML文件。但是,當顯示我收到問號。有人可以研究這個問題嗎?無法解析包含中文內容的XML文件
我是book.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<book>
<person>
<first>密碼</first>
<last>Pai</last>
<age>22</age>
</person>
</book>
而且我的代碼是:
public static void main (String argv []){
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));
String strDoc=getStringFromDocument(doc);
System.out.println(strDoc);
}
public static String getStringFromDocument(Document doc) {
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString.toString();
}
我越來越??
之後:
<?xml version="1.0" encoding="UTF-8"?>
<book>
<person>
<first>??</first>
<last>Pai</last>
<age>22</age>
</person>
我必須設置-Dfile.encoding = ISO-8859-1? – Peter
取決於你的環境。從命令中將「java ...」替換爲「java -Dfile.encoding = ISO-8859-1 ...」。使用IDE只需按照IDE的說明將其添加到調試時指定「VM選項」或「VM參數」的任何位置。 –