2011-03-03 263 views
0

我一直在使用xml文件保存我的java程序中的數據。我正在使用java DOM api。我想通過添加一個元素然後將子元素添加到該元素來添加到文檔中。 我試着用這段代碼做,但是當我運行它時,它什麼都不做。有沒有另外一種方法可以做到簡單,並且效果更好?有沒有辦法讓我的代碼工作?如何在java中追加xml文件

File file = new File("C:/users/peter/desktop/newxml.xml"); 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    Document document = db.parse(file); 
    Element newB = document.createElement("B"); 
    Element newC = document.createElement("c"); 
    newC.setTextContent("11"); 
    Element newD = document.createElement("d"); 
    newD.setTextContent("21"); 
    Element newE = document.createElement("e"); 
    newE.setTextContent("31"); 
    newB.appendChild(newC); 
    newB.appendChild(newD); 
    newB.appendChild(newE); 
    document.getDocumentElement().appendChild(newB); 
+0

簡單 - 它「什麼也不做」是你的代碼是不是寫出來的DOM,一旦你做出改變的原因s到內存數據結構。 – 2011-03-03 03:43:06

+0

通過使用帶有空變換(樣式表)的Transformer並且目標是StreamResult,可以寫出一個dom。 – MeBigFatGuy 2011-03-03 04:29:37

+0

我將如何添加到我的代碼? – Peter 2011-03-03 12:36:58

回答

0

您應該查看JAXB API。如果我理解正確的,你的XML是這樣的:

<B> 
    <C>11</C> 
    <D>21</D> 
    <E>31</E> 
</B> 

因此,代碼如下:

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlAccessType; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class B { 
    @XmlElement public String C; // sloppy, probably should be type Integer or something 
    @XmlElement public String D; 
    @XmlElement public String E; 
} 

// then, somewhere else in your code you want to serialize... 
B b = new B(); 
b.C = "11"; 
b.D = "21"; 
b.E = "31"; 

JAXBContext c = JAXBContext.newInstance(B.class); 

// where w is a Writer instance 
c.createMarshaller().marshal(b, w); 
+0

不錯downvote。有什麼特別的原因?! – Kevin 2012-03-12 14:32:08

1

這java代碼工程,以新的節點追加到XML文件......它是基於DOM

import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
import java.io.FileOutputStream; 
public class writexml1 { 

public static void main (String args[]) 
{ 

File docFile = new File("..\\jquery\\WebContent\\demo\\testing.xml"); 

Document doc = null; 
try 
{ 
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
doc = db.parse(docFile); 
} 
catch (java.io.IOException e) 
{ 
System.out.println("Can't find the file"); 
} 
catch (Exception e) 
{ 
System.out.print("Problem parsing the file."); 
} 

Element root = doc.getDocumentElement(); 

System.out.println("The root element is " + root.getNodeName() + ".\n"); 

NodeList children = root.getChildNodes(); 
System.out.print("There are "+children.getLength()+" child elements.\n"); 
System.out.print("They are: \n"); 

//Print the file 
for (Node child = root.getFirstChild();child != null;child = child.getNextSibling()) 
{ 
if (child.getNodeType() == child.TEXT_NODE) 
{ 
System.out.println("Text: "+child.getNodeValue()); 
} 
else if (child.getNodeType() == child.ELEMENT_NODE) 
{ 
System.out.println(child.getNodeName()+" = "+child.getFirstChild().getNodeValue()); 
} 
} 


//NodeList deleteElement = root.getElementsByTagName("staff"); 

//Node deleteNode= deleteElement.item(0); 

//root.removeChild(deleteNode); 
Element staffElement = doc.createElement("staff"); 

Node updateText = doc.createTextNode(""); 
staffElement.appendChild(updateText); 
// 
Element firstName = doc.createElement("firstname"); 
String str_firstName="added firstname"; 
Node firstNameNode = doc.createTextNode(str_firstName); 
firstName.appendChild(firstNameNode); 

staffElement.appendChild(firstName); 

// 

Element lastName = doc.createElement("lastname"); 
String str_lastName="added lastname"; 
Node lastNameNode = doc.createTextNode(str_lastName); 
lastName.appendChild(lastNameNode); 

staffElement.appendChild(lastName); 


// 
Element nickName = doc.createElement("nickname"); 
String str_nickName="added nickname"; 
Node nickNameNode = doc.createTextNode(str_nickName); 
nickName.appendChild(nickNameNode); 

staffElement.appendChild(nickName); 


// 
Element salary = doc.createElement("salary"); 
String str_salary="$10,000"; 
Node salaryNode = doc.createTextNode(str_salary); 
salary.appendChild(salaryNode); 

staffElement.appendChild(salary); 


// 
root.appendChild(staffElement); 

//Node StaffNode=(Node)updateElement; 





try{ 
String outputURL = "..\\jquery\\WebContent\\demo\\testing.xml"; 

DOMSource source = new DOMSource(doc); 
StreamResult result = new StreamResult(new FileOutputStream(outputURL)); 

TransformerFactory transFactory = TransformerFactory.newInstance(); 
Transformer transformer = transFactory.newTransformer(); 

transformer.transform(source, result); 

} catch (Exception e) { 
e.printStackTrace(); 
} 

} 

}