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

Java创建新的xml文件并附加它,java,xml,xml-parsing,sax,saxparser,Java,Xml,Xml Parsing,Sax,Saxparser,我开发了一种方法,可以获取一个列表集合,其中包含需要写入XML文件的数据。首先,我检查文件的存在性,根据文件的存在性,我要么创建一个新文件并写入数据,要么追加数据 我无法找出错误在哪里,我已经检查了以下链接,但我认为我远远超出了解决方案 它首先成功地创建了文件,在这一点上没有问题,但是当它添加文件时,我确实面临着一个例外: 文档中根元素后面的标记必须格式正确。 createXMLFile org.xml.sax.saxpasseException中的异常;系统ID: 示例xml文件是: <

我开发了一种方法,可以获取一个列表集合,其中包含需要写入XML文件的数据。首先,我检查文件的存在性,根据文件的存在性,我要么创建一个新文件并写入数据,要么追加数据

我无法找出错误在哪里,我已经检查了以下链接,但我认为我远远超出了解决方案

它首先成功地创建了文件,在这一点上没有问题,但是当它添加文件时,我确实面临着一个例外:

文档中根元素后面的标记必须格式正确。 createXMLFile org.xml.sax.saxpasseException中的异常;系统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;
    }

数据
数据1
数据2
数据3
数据4
数据5
受保护的布尔文件存在(字符串文件路径){
if(新文件(filePath).isFile())
返回新文件(filePath).exists();
返回false;
}
公共文件写入(列表语句数据){
File=null;
试一试{
最终字符串文件名=getWorkingPath()+FileConstants.XML\u文件名;
布尔fileExist=fileExists(文件名);
DocumentBuilderFactory docFactory=DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
单据单据=空;
如果(文件存在)
doc=docBuilder.parse(文件名);
其他的
doc=docBuilder.newDocument();
//文本元素
元素rootElement=doc.createElement(“文本”);
doc.appendChild(rootElement);
//遍历句子数据
ListIterator ListIterator=sentenceData.ListIterator();
while(listIterator.hasNext()){
句子obj=(句子)listIterator.next();
//句子成分
元素句子=doc.createElement(“句子”);
根元素。追加子元素(句子);
//反复阅读句子中的单词
for(字符串wordListData:obj.getWordList()){
字符串wordData=wordListData;
//句子中的词成分
元素词=doc.createElement(“词”);
appendChild(doc.createTextNode(wordData));
句子。追加儿童(单词);
}
//移除该元素
remove();
}
//将内容写入xml文件
Transformer Transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,“是”);
StreamResult=新的StreamResult(新的FileWriter(文件名));
DOMSource=新的DOMSource(doc);
变换(源、结果);
}捕获(ParserConfiguration异常e){
logger.error(“createXMLFile中的异常”+e);
}捕获(转换异常e){
logger.error(“createXMLFile中的异常”+e);
}捕获(SAXE异常){
logger.error(“createXMLFile中的异常”+e);
}捕获(IOE异常){
logger.error(“createXMLFile中的异常”+e);
}
返回文件;
}
编辑: 我发现我错过了什么,很高兴能在这里给出答案,但我迟到了:)下面是你可以找到的完整源代码。希望它将来能帮助其他人

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;

}
公共文件写入(列表语句数据){
最终字符串文件名=getWorkingPath()+FileConstants.XML\u文件名;
最终布尔值fileExist=fileExists(文件名);
文件=新文件(文件名);
试一试{
DocumentBuilderFactory docFactory=DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
单据单据=空;
元素textElement=null;
//根据文件是否存在继续
如果(文件存在){
//文件存在
doc=docBuilder.parse(文件);
textElement=doc.getDocumentElement();
//遍历句子数据
ListIterator ListIterator=sentenceData.ListIterator();
while(listIterator.hasNext()){
句子obj=(句子)listIterator.next();
Element sentenceElement=doc.createElement(“句子”);
//遍历单词列表
for(字符串字:obj.getWordList()){
Element wordElement=doc.createElement(“word”);
appendChild(doc.createTextNode(word));
sentenceElement.appendChild(wordElement);
}
extElement.appendChild(sentenceElement);
}
}否则{
//文件不存在
doc=docBuilder.newDocument();
textElement=doc.createElement(“文本”);
doc.appendChild(textElement);
//遍历句子数据
ListIterator ListIterator=sentenceData.ListIterator();
while(listIterator.hasNext()){
句子obj=(句子)listIterator.next();
//句子成分
Element sentenceElement=doc.createElement(“句子”);
extElement.appendChild(sentenceElement);
//反复阅读句子中的单词
for(字符串wordListData:obj.getWordList()){
字符串wordData=wordListData;
//句子中的词成分
Element wordElement=doc.createElement(“word”);
appendChild(doc.createTextNode(wordData));
sentenceElement.appendChild(wordElement);
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 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
}