2012-03-13 88 views
2

我有一個XML文件,其中包含一個元素,如圖所示;以Java編寫XML文件

"<Event start="2011.12.12 13:45:00:0000" end="2011.12.12 13:47:00:0000" anon="89"/>" 

我想添加另一個屬性「評論」,並將其寫入此XML文件給;

"<Event start="2011.12.12 13:45:00:0000" end="2011.12.12 13:47:00:0000" anon="89" comment=""/>" 

我該怎麼做呢?

謝謝,馬特

+0

有一個在我回答另一個問題工作的完整示例:http://stackoverflow.com/a/9588830/898289 – Adam 2012-03-13 12:37:22

回答

0

使用的setAttribute方法添加屬性,

// Add an attribute 
element.setAttribute("newAttrName", "attrValue"); 

使用下面的方法寫XML文件,

// This method writes a DOM document to a file 
public static void writeXmlFile(Document doc, String filename) { 
    try { 
     // Prepare the DOM document for writing 
     Source source = new DOMSource(doc); 

     // Prepare the output file 
     File file = new File(filename); 
     Result result = new StreamResult(file); 

     // Write the DOM document to the file 
     Transformer xformer = TransformerFactory.newInstance().newTransformer(); 
     xformer.transform(source, result); 
    } catch (TransformerConfigurationException e) { 
    } catch (TransformerException e) { 
    } 
} 
+0

感謝您的幫助! :D 現已完成! – user1224534 2012-03-13 12:41:37

+0

最受歡迎:) – 2012-03-13 12:44:02

0

解析文件,添加屬性並將其寫回到磁盤。

有很多框架可以做到這一點。 Java中的DOM框架可能是您應該關注的第一件事。

+0

我已經解析XML文件中的所有元素,並我試圖設置屬性(「評論」,「」)。但它什麼都不做。 – user1224534 2012-03-13 12:11:29

2
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
factory.setIgnoringElementContentWhitespace(true); 
Document document = factory.newDocumentBuilder().parse(xmlFile); 

Element eventElement = (Element)document.getElementsByTagName("Event").item(0); 
eventElement.setAttribute("comment", ""); 

FYI:我在這裏使用DOM框架org.w3c.dom.*

+0

感謝您的幫助! :) – user1224534 2012-03-13 12:41:52

0

正如前面的答案所建議的那樣,使用DOM對於這個特殊情況來說當然是合理的這個問題比較簡單。

但是,我發現,當您要解析和/或修改XML文件時,JDOM通常更容易使用。其基本方法是將整個文件加載到易於使用的數據結構中。這很好,除非你的XML文件非常大。

欲瞭解更多信息請訪問http://www.jdom.org/