2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
XML 閱讀應(yīng)該<row>大致如下:
XMLInputFactory xif = XMLInputFactory.newInstance();
// Do not use a Reader, especially not a FileReader. An InputStream leaves the
// encoding of the XML to the XMLStreamReader.
InputStream in = Files.newInputStream(Paths.get("D:/SmallXmltoSplit.xml"));
XMLStreamReader streamReader = xif.createXMLStreamReader(in);
streamReader.nextTag();
String id = "";
String name = "";
String deptId = "";
String oldDeptId = null;
// File file = new File("D:/test" + ".xml");
while (streamReader.hasNext()) {
if (streamReader.isStartElement()) {
switch (streamReader.getLocalName()) {
case "row":
id = "";
name = "";
deptId = "";
break;
case "id":
id = streamReader.getElementText();
break;
case "name":
name = streamReader.getElementText();
break;
case "deptId":
deptId = streamReader.getElementText();
break;
}
}
if (streamReader.isEndElement()) {
switch (streamReader.getLocalName()) {
case "START":
if (oldDeptId != null) {
saveDept();
//oldDeptId = deptId;
}
break;
case "row":
if (!deptId.equals(oldDeptId)) {
if (oldDeptId != null) {
saveDept();
oldDeptId = deptId;
}
startDept(deptId);
}
appendDeptRow(id, name, deptId);
break;
}
}
}
無需轉(zhuǎn)換即可書寫;事實(shí)上,它可以作為文本完成。
我把它留作練習(xí)。
不應(yīng)使用 FileReader 和 FileWriter,因?yàn)樗鼈兪褂媚J(rèn)平臺(tái)編碼對字節(jié)進(jìn)行編碼。這個(gè)類Files有很多不錯(cuò)的文件函數(shù)。
這里的另一個(gè)特色是 UTF-16 編碼,它將幾乎是 ASCII 文件的大小加倍。當(dāng)您提到有一個(gè)大文件時(shí),最好將該文件保存在 UTF-8 中,可能即使名稱是波斯語、希臘語、日語或保加利亞語。
添加回答
舉報(bào)