2011-03-03 217 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(); 
} 

} 

}