Java xml add node

How to append xml file in java

I’ve been using xml files to save data from my java program. I’m using the java DOM api. I want to add to the document by adding an element and then adding children to that element. I tried doing it using this code but when i run it it does nothing. Is there another way of doing it that would be simple and work better? is there a way i can get this code working?

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); 

Briefly — the reason that it «does nothing» is that your code is not writing out the DOM once you’ve made the changes to the in-memory data structure.

You can write out a dom, by using a Transformer with a null transform (stylesheet) and the destination being a StreamResult.

2 Answers 2

This java code works to append new node to the xml file. it is based on 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(); >> 

Источник

Читайте также:  Python serialize with json

Add new node in XML file

If the RegDef node have a < i >node I want to read the text fron the < i >node and write a < w >node for each word. I tried to use XPath like below:

 Element rootElement = document.getDocumentElement(); Element element = document.createElement("w"); rootElement.appendChild(element); 

but it appends right after the root node. How can i write a node for each word in RegDef tag and then add an attribute to that node? Thank you.

1 Answer 1

You selected the root node of your file . If you use appendChild on that node, your node will be appended as the last child of the root node, which is the expected behaviour.

You actually want to wrap words inside the RegDef node with the w element, which is not a task as simple as the three lines of code you included in your example.

For that you will need to:

  1. Select that node (there are many methods in the DOM, document.getElementsByTagName(«RegDef») will give you a NodeList containing all of them. You can also use XPath.
  2. For each RegDef you will need to select all its descendant text nodes. If you use XPath an expression such as .//text() in the context of each RegDef will give you a list of those nodes. Each one may contain one or more «words», or even empty spaces and newlines.
  3. You can extract the words by splitting by spaces or punctuation marks or other characters that can be used as delimiters for a word. There are several tools for that in Java, including regular expressions.
  4. Finally, when you have isolated each individual «word», and eliminated the nodes you want to ignore, you can create a w element for each one, create a new text node containing the word, and append the text node as a child of that element. You will also have to set attributes.

Perhaps you should use a smaller XML file to focus on your specific problem, and later adapt it to your real world example. You could start with something like this:

String xml = "\n" + " This text have i node.\n" + " This text doesn't have i atribute.\n" + ""; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xml))); NodeList regDefNodes = document.getElementsByTagName("RegDef"); int size = regDefNodes.getLength(); for(int i = 0; i

Now you can use the steps above as a guide and write the wrapWordsInContents(Element e, Document doc) method.

UPDATE: You asked about tokenizing the content in a followup question which contains the wrapWordsInContents(Element e, Document doc) method. After you call that method and serialize the code above with:

Transformer t = TransformerFactory.newInstance().newTransformer(); t.transform(new DOMSource(document), new StreamResult(System.out)); 

you will have a result similar to the one you expect. See your followup question: Modify the text content of XML tag

Источник

How do I append a node to an existing XML file in java

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml . It does not work without an existing .xml file, so you will need to modify the code to handle that case.

import java.util.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import javax.xml.transform.dom.*; import org.w3c.dom.*; import javax.xml.parsers.*; public class AddXmlNode < public static void main(String[] args) throws Exception < DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse("server.xml"); Element root = document.getDocumentElement(); Collectionservers = new ArrayList(); servers.add(new Server()); for (Server server : servers) < // server elements Element newServer = document.createElement("server"); Element name = document.createElement("name"); name.appendChild(document.createTextNode(server.getName())); newServer.appendChild(name); Element port = document.createElement("port"); port.appendChild(document.createTextNode(Integer.toString(server.getPort()))); newServer.appendChild(port); root.appendChild(newServer); >DOMSource source = new DOMSource(document); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StreamResult result = new StreamResult("server.xml"); transformer.transform(source, result); > public static class Server < public String getName() < return "foo"; >public Integer getPort() < return 12345; >> > 

The main change to your code is not creating a new «root» element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

Источник

How to insert a xml node as first child in another xml document in java?

I’ll be really irritated if it turns out I just did your homework for you.

package com.akonizo.examples; import java.io.ByteArrayInputStream; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class XmlInsertExample < /** * @param args */ public static void main(String[] args) < String initial = ""; try < // Parse the initial document ByteArrayInputStream is = new ByteArrayInputStream(initial.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); // Create the new xml fragment Text a = doc.createTextNode("afds"); Node p = doc.createElement("parameterDesc"); p.appendChild(a); Node i = doc.createElement("insert"); i.appendChild(p); Element r = doc.getDocumentElement(); r.insertBefore(i, r.getFirstChild()); r.normalize(); // Format the xml for output Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); System.out.println(result.getWriter().toString()); >catch (Exception e) < e.printStackTrace(); >> > 

Источник

Append nodes into existing XML File with java

what i whant to add is a person node with its elements inside the people element. My big problem is the data node which is root node. If it would be the Person node as root I could solve it. But I can’t manage to get the person nodes under the people node.

Element root = document.getDocumentElement(); // Root Element Element rootElement = document.getDocumentElement(); Collection svr = new ArrayList(); 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); 

Источник

Оцените статью