2015-11-24 45 views
0

我開發了一種方法,它獲取需要寫入XML文件的數據的List集合。首先,我檢查存在的文件,這取決於存在我要麼創建一個新的文件,並寫入數據或附加數據Java創建一個新的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

我這裏模擬你的代碼並沒有意識到你是不是在創建XML文件的有效根元素,這就是爲什麼你得到例外。

看到我的結果我正在運行的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); 
} 

句類:

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

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> 

解決方案: 只需更換您的代碼如下:

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

感謝您的答覆和解決方案aelkz!這是我第一次使用lib,我很高興在這裏分享我的結果,但你是第一次:)我完全錯過了差異! –

相關問題