嗨,即時通訊尋找一種解決方案,將Java節點追加到現有的XML文件。 我得到的是這樣的使用java將節點追加到現有的XML文件
<data>
<people>
<person>
<firstName>Frank</firstName>
<lastName>Erb</lastName>
<access>true</access>
<images>
<img>hm001.jpg</img>
</images>
</person>
<person>
<firstName>Hans</firstName>
<lastName>Mustermann</lastName>
<access>true</access>
<images>
<img>hm001.jpg</img>
</images>
</person>
<person>
<firstName>Thomas</firstName>
<lastName>Tester</lastName>
<access>false</access>
<images>
<img>tt001.jpg</img>
</images>
</person>
</people>
</data>
一個XML文件我whant補充的是與它的人民元素中的元素一個人節點。我的大問題是作爲根節點的數據節點。如果它將作爲根節點,我可以解決它。但我無法設法讓人節點下的人節點。
<person>
<firstName>Tom</firstName>
<lastName>Hanks</lastName>
<access>false</access>
<images>
<img>tt001.jpg</img>
</images>
</person>
感謝您的幫助!
我的Java代碼看起來就這樣
Element root = document.getDocumentElement();
// Root Element
Element rootElement = document.getDocumentElement();
Collection<Server> svr = new ArrayList<Server>();
svr.add(new Server());
for (Server i : svr) {
// server elements
Element server = document.createElement("people");
rootElement.appendChild(server);
//rootElement.appendChild(server);
Element name = document.createElement("person");
server.appendChild(name);
Element firstName = document.createElement("firstName");
firstName.appendChild(document.createTextNode(i.getFirstName()));
server.appendChild(firstName);
name.appendChild(firstName);
Element port = document.createElement("lastName");
port.appendChild(document.createTextNode(i.getLastName()));
server.appendChild(port);
name.appendChild(port);
Element access = document.createElement("access");
access.appendChild(document.createTextNode(i.getAccess()));
server.appendChild(access);
name.appendChild(access);
String imageName = Main.randomImgNr+"";
Element images = document.createElement("images");
//images.appendChild(document.createTextNode(i.getAccess()));
Element img = document.createElement("img");
img.appendChild(document.createTextNode(imageName));//i.getImage()));
images.appendChild(img);
server.appendChild(images);
name.appendChild(images);
root.appendChild(server);
試過使用JAXB?它非常整齊。 –