我开发了一种获取List集合的方法,其中数据需要写入XML文件。首先,我检查文件是否存在,具体取决于是否存在我创建新文件并写入数据或附加数据
我无法找出错误的位置,我已经检查了下面的链接,但我认为我远远超出了解决方案。
http://www.coderanch.com/t/561569/XML/Appending-data-existing-XML-file
它首先成功创建了文件,此时没有任何问题,但是当它附加文件时我确实面临异常:
根元素后面的文档中的标记必须格式正确。 createXMLFile org.xml.sax.SAXParseException中的异常;的systenId:
示例xml文件是:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<text>
<sentence>
<word>data</word>
<word>data1</word>
<word>data2</word>
<word>data3</word>
<word>data4</word>
<word>data5</word>
</sentence>
</text>
protected boolean fileExists(String filePath) {
if (new File(filePath).isFile())
return new File(filePath).exists();
return false;
}
public File write(List<Sentence> sentenceData) {
File file = null;
try {
final String fileName = getWorkingPath() + FileConstants.XML_FILE_NAME;
boolean fileExist = fileExists(fileName);
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = null;
if(fileExist)
doc = docBuilder.parse(fileName);
else
doc = docBuilder.newDocument();
// text element
Element rootElement = doc.createElement("text");
doc.appendChild(rootElement);
// Iterate through sentence data
ListIterator<Sentence> listIterator = sentenceData.listIterator();
while (listIterator.hasNext()) {
Sentence obj = (Sentence) listIterator.next();
// sentence elements
Element sentence = doc.createElement("sentence");
rootElement.appendChild(sentence);
// Iterate through words in the sentence
for (String wordListData : obj.getWordList()) {
String wordData = wordListData;
// word elements in a sentence
Element word = doc.createElement("word");
word.appendChild(doc.createTextNode(wordData));
sentence.appendChild(word);
}
// remove the element
listIterator.remove();
}
// write the content into xml file
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new FileWriter(fileName));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
logger.error("Exception in createXMLFile " + e);
} catch (TransformerException e) {
logger.error("Exception in createXMLFile " + e);
} catch (SAXException e) {
logger.error("Exception in createXMLFile " + e);
} catch (IOException e) {
logger.error("Exception in createXMLFile " + e);
}
return file;
}
编辑: 我发现了我错过的内容,并且很高兴在这里提出答案,但我迟到了:)下面是您可能找到的完整源代码。希望将来能帮助其他人。
public File write(List<Sentence> sentenceData) {
final String fileName = getWorkingPath() + FileConstants.XML_FILE_NAME;
final boolean fileExist = fileExists(fileName);
File file = new File(fileName);
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = null;
Element textElement = null;
//Proceed depending on file existence
if(fileExist){
//File exists
doc = docBuilder.parse(file);
textElement = doc.getDocumentElement();
// Iterate through sentence data
ListIterator<Sentence> listIterator = sentenceData.listIterator();
while (listIterator.hasNext()) {
Sentence obj = (Sentence) listIterator.next();
Element sentenceElement = doc.createElement("sentence");
//Iterate through word list
for(String word : obj.getWordList()){
Element wordElement = doc.createElement("word");
wordElement.appendChild(doc.createTextNode(word));
sentenceElement.appendChild(wordElement);
}
textElement.appendChild(sentenceElement);
}
}else{
//File does not exist
doc = docBuilder.newDocument();
textElement = doc.createElement("text");
doc.appendChild(textElement);
// Iterate through sentence data
ListIterator<Sentence> listIterator = sentenceData.listIterator();
while (listIterator.hasNext()) {
Sentence obj = (Sentence) listIterator.next();
// sentence elements
Element sentenceElement = doc.createElement("sentence");
textElement.appendChild(sentenceElement);
// Iterate through words in the sentence
for (String wordListData : obj.getWordList()) {
String wordData = wordListData;
// word elements in a sentence
Element wordElement = doc.createElement("word");
wordElement.appendChild(doc.createTextNode(wordData));
sentenceElement.appendChild(wordElement);
}
}
}
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
logger.error("Exception in write " + e);
} catch (SAXException e) {
logger.error("Exception in write " + e);
} catch (IOException e) {
logger.error("Exception in write " + e);
} catch (TransformerConfigurationException e) {
logger.error("Exception in write " + e);
} catch (TransformerFactoryConfigurationError e) {
logger.error("Exception in write " + e);
} catch (TransformerException e) {
logger.error("Exception in write " + e);
}
return file;
}
答案 0 :(得分:0)
我在这里模拟了您的代码并且意识到您没有在XML文件中创建有效的根元素,这就是您获得异常的原因。
查看我的结果,我正在运行write方法:
x = x.replaceAll("\"", "\\\\\"");
句子类:
public static void main(String... x) {
Sentence s = new Sentence();
Main m = new Main();
List<Sentence> list = new ArrayList<Sentence>();
list.add(s);
m.write(list);
}
file.xml:
public class Sentence {
public String[] getWordList() {
return new String[] { "w4", "w5", "w6" }; // previous: w1,w2,w3
}
}
解决方案: 只需使用以下代码替换您的代码:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<text>
<sentence>
<word>w1</word>
<word>w2</word>
<word>w3</word>
</sentence>
<sentence>
<word>w4</word>
<word>w5</word>
<word>w6</word>
</sentence>
<sentence>
<word>w4</word>
<word>w5</word>
<word>w6</word>
</sentence>
</text>