gpt4 book ai didi

Java 创建一个新的 xml 文件并附加它

转载 作者:太空宇宙 更新时间:2023-11-04 13:11:41 25 4
gpt4 key购买 nike

我开发了一种获取 List 集合的方法,其中的数据需要写入 XML 文件。首先,我检查文件是否存在,根据是否存在,我创建一个新文件并写入数据或附加数据

我找不到错误所在,我检查了以下链接,但我认为我远远超出了解决方案。

http://www.coderanch.com/t/561569/XML/Appending-data-existing-XML-file

它首先成功创建了文件,当时没有问题,但是当它确实要附加文件时,我确实遇到了异常:

文档中根元素后面的标记必须格式正确。 createXMLFile org.xml.sax.SAXParseException 中出现异常;系统ID:

示例 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;

}

最佳答案

我在这里模拟了您的代码,并意识到您没有在 XML 文件中创建有效的根元素,这就是您收到异常的原因。

查看我运行写入方法的结果:

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);
}

句子类别:

public class Sentence {
public String[] getWordList() {
return new String[] { "w4", "w5", "w6" }; // previous: w1,w2,w3
}
}

文件.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>

解决方案:只需将您的代码替换为以下内容即可:

// text element
Element rootElement = null;
if (!fileExist) {
rootElement = doc.createElement("text");
doc.appendChild(rootElement);
} else {
rootElement = doc.getDocumentElement(); // get the root [text] element
}

关于Java 创建一个新的 xml 文件并附加它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33892711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com