[英]Java creating a new xml file and appending it
I've developed a method which acquires a List collection with data needs to be written to an XML file. 我已经开发了一种方法,该方法可获取需要将数据写入XML文件的List集合。 First of all I check the existence of the file, depending on the existence I either create a new file and write the data or append the data 首先,我检查文件的存在,根据存在的情况,我创建一个新文件并写入数据或追加数据
I could not find out where the mistake is, I've checked the below links but I think I am far beyond the solution. 我无法找出错误所在,已经检查了以下链接,但我认为我远远不能解决问题。
http://www.coderanch.com/t/561569/XML/Appending-data-existing-XML-file http://www.coderanch.com/t/561569/XML/Appending-data-existing-XML-file
It first created the file successfully there is no issue at that point, but when it does come to appending the file I do face the exception: 它首先成功地成功创建了文件,这时没有问题,但是在添加文件时确实遇到了一个例外:
The markup in the document following the root element must be well-formed. 根元素后面的文档中的标记必须格式正确。 Exception in createXMLFile org.xml.sax.SAXParseException; createXMLFile org.xml.sax.SAXParseException中的异常; systemId: systemId:
Sample xml file is: 样本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;
}
Edit: I've found out what I missed, and thrilled to put the answer here but I was late :) the below the full source code you may find. 编辑:我发现了我错过的内容,很高兴将答案放在这里,但我来晚了:)下面是您可能找到的完整源代码。 Hope it will help the others in the future. 希望将来对其他人有帮助。
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;
}
I simulated your code here and did realized the you are not creating a valid root element in XML file, that's why you getting the exception. 我在这里模拟了您的代码,并意识到您没有在XML文件中创建有效的根元素,这就是为什么您遇到异常的原因。
See my results that I am getting running the write method: 查看我正在运行write方法的结果:
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);
}
Sentence class: 句子类:
public class Sentence {
public String[] getWordList() {
return new String[] { "w4", "w5", "w6" }; // previous: w1,w2,w3
}
}
file.xml: file.xml:
<?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>
Solution: Just replace your code with the following: 解决方案:只需将代码替换为以下内容:
// text element
Element rootElement = null;
if (!fileExist) {
rootElement = doc.createElement("text");
doc.appendChild(rootElement);
} else {
rootElement = doc.getDocumentElement(); // get the root [text] element
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.