I try to write a simple XML file in Java using the DocumentBuilder.
I expected the XML file to look like this:
<outer>
<inner>
<element name="WEB"/>
<element name="WEB"/>
<element name="WEB"/>
</inner>
</outer>
But it generates it like this:
<outer>
<inner>
<element name="WEB"/>
<element name="WEB"/>
<element name="WEB"/>
</inner>
</outer>
Why the third element does not have the same indentation as the other two elements?
Note: I read the XML file again to simulate a method in a project, where I read an XML file, add one element and save it to the XML file.
Here is my code:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
public class main {
private static String FILEPATH = "/tmp/xmltest.xml";
private static DocumentBuilderFactory docFactory;
private static DocumentBuilder docBuilder;
private static TransformerFactory transformerFactory;
private static Transformer transformer;
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException{
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
transformerFactory= TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
// Creating the XML file structure
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("outer");
document.appendChild(rootElement);
Element inner = document.createElement("inner");
rootElement.appendChild(inner);
// Write XML file
write(document);
// Read XML file
document = docBuilder.parse(FILEPATH);
Element root = document.getDocumentElement();
Element innerElement = (Element)root.getElementsByTagName("inner").item(0);
// Add element
Element e = document.createElement("element");
e.setAttribute("name", "WEB");
innerElement.appendChild(e);
// Add element
e = document.createElement("element");
e.setAttribute("name", "WEB");
innerElement.appendChild(e);
// Write XML file
write(document);
// Read XML fil
document = docBuilder.parse(FILEPATH);
root = document.getDocumentElement();
innerElement = (Element)root.getElementsByTagName("inner").item(0);
// Add element
e = document.createElement("element");
e.setAttribute("name", "WEB");
innerElement.appendChild(e);
// Write XML file
write(document);
}
private static void write(Document document) throws TransformerException {
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(FILEPATH));
transformer.transform(source, result);
}
}
the text nodes in xmlfile used for indententation are treated as data. because of this your indentation is going for toss. you can fix this as below:
private static void removeEmptyText(Node node){
Node child = node.getFirstChild();
while(child!=null){
Node sibling = child.getNextSibling();
if(child.getNodeType()==Node.TEXT_NODE){
if(child.getTextContent().trim().isEmpty())
node.removeChild(child);
}else
removeEmptyText(child);
child = sibling;
}
}
private static void write(Document document) throws TransformerException {
removeEmptyText(document.getDocumentElement());
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(FILEPATH));
transformer.transform(source, result);
}
here i am removing all indentation text nodes from dom before writing to file.
Related
I have this string containing my request xml. I want to delete below "id" tags from this string if they exist and return it back. Removing "Identity" completely will also work, if that can be done.
To be deleted :
<Identity>
<id extension="7865232" aan = "BUH"/>
<code/>
</Identity>
<Identity>
<id extension="88769032" aan = "DIH"/>
<code/>
</Identity>
String XMLString= "<request version ="1.0">
<minMatch>
<val>100</val>
</minMatch>
<paramList>
<payLoad display = "Full" type="F">
</payLoad>
<IQC code = "2">
</IQC>
<Control display="Default" type = "D">
</Control>
<member>
<memCode code = "Active"
</memCode>
<id extension="12345" aan="ACC"></id>
<id extension="54321" aan="REQ"></id>
<id extension="554376" aan="PDR"></id>
<id extension="66321" aan="NJQ"></id>
<addr use = "H">
<streetLine>123</streetLine>
<city>POLIS</city>
<state>NY</state>
<postalCode>44321</postalCode>
</addr>
<telecom value = "5543213">
</telecom>
<Person>
<name>
<given>JOHN</given>
<family>BILL</family>
</name>
<GenderCode code ="M" display="Male">
</GenderCode>
<birthime vaue="19651002">
</birthime>
<Identity>
<id extensio="7865232" aan = "BUH"/>
<code/>
</Identity>
<Identity>
<id extensio="88769032" aan = "DIH"/>
<code/>
</Identity>
</Person>
</member>
----
---
</request>"
I am using below code to achieve the same but it's not working and giving me The constructor DOMSource(Document) is undefined. I tired converting document into a byte Array but that's also not working.Is there any way i can simply do this in Java 1.8. Any other approach is also welcome.
Please suggest.Thank you!
public void removeIds(String xmlString){
Document doc = null;
SAXBuilder saxbuilder = new SAXBuilder();
try{
doc = saxbuilder.build(new StringReader(xmlString));
}catch(JDOMException je){
je.printStackTrace();
}catch(IOException ie){
ie.printStackTrace();
}
Element rootNode = doc.getRootElement();
IteratorIterable<Element> rootChildren=rootNode.getDescendants(new ElementFilter("Person"));
for(Element Person:rootChildren){
for(Element Identity:Person.getChildren("Identity")){
((Element) doc.getRootElement.getDescendants(new ElementFilter("Identity"))).removeChild("id");
}
}
try{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
transformer = tf.newTransformer();
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
}
Since you're invoking a transformation anyway, it's much simpler to do all the work in XSLT rather than fiddle about with low-level DOM manipulation.
If you use XSLT 3.0 (Saxon) then the stylesheet is simply
<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output indent="yes" encoding="utf-8"/>
<xsl:template match="id"/>
</xsl:transform>
You can supply the input to this transformation as new StreamSource(new StringReader(xmlString)) -- there's no need to construct a DOM first.
It can be done in XSLT 1.0 too (i.e. with Xalan, which comes bundled with the JDK), but is a bit more verbose.
Here is solution using XPath API. In this example all elements "id" inside elements "Identity" are removed (XPath expression "//Identity/id"). If you want to remove all id elements, change it to "//id".
import java.io.StringReader;
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 javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
// function for XML serialization
public static String serialize(Document document) {
removeWhitespaces(document.getDocumentElement());
try (StringWriter writer = new StringWriter()) {
StreamResult result = new StreamResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(document), result);
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// helper function for stripping whitespaces
public static void removeWhitespaces(Element element) {
NodeList children = element.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i--) {
Node child = children.item(i);
if (child instanceof Text
&& ((Text) child).getData().trim().isEmpty()) {
element.removeChild(child);
} else if (child instanceof Element) {
removeWhitespaces((Element) child);
}
}
}
Main code:
// parse XML
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
// find id elements
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//Identity/id");
NodeList nodes = (NodeList)xpath.evaluate(doc, XPathConstants.NODESET);
// remove found elements
for(int i = 0; i < nodes.getLength(); i ++) {
Node node = nodes.item(i);
node.getParentNode().removeChild(node);
}
// serialize and output document
String result = serialize(doc);
System.out.println(result);
I am trying to remove an attributs from an org.w3c.dom.Element.
When using removeAttribute the attribut-name (with an default value) is still contained in the resulting XML (in this case a SVG file).
In the JavaDoc I found the following explanation:
If a default value for the removed attribute is defined in the DTD, a new attribute immediately appears with the default value as well as the corresponding namespace URI, local name, and prefix when applicable.
How can I avoid this behaviour? I can not change the DTD. I just want to get rid of this attribut.
Edit:
T.J. Crowder asked me for a minimal example.
import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class MinimalExample {
public static void main(String[] args) throws Exception {
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
Document doc = f.createDocument("batik.svg");
Element svg = doc.getDocumentElement();
svg.removeAttribute("contentStyleType");
System.out.println(getXML(doc));
}
public static String getXML(Document doc) throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
return writer.toString();
}
}
I am trying to insert a new node within an exsting node for N number of times, however it is not working for me, following is what I am doing:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filePath);
Node pNode = doc.getElementsByTagName(parentNode).item(0);
for (int i = 1; i <= count; i++) {
String nodeValue = value;
Element newNode = doc.createElement(childNode);
newNode.appendChild(doc.createTextNode(nodeValue));
pNode.appendChild(newNode);
}
This is what I am trying to achieve:
<parentNode>
<childNode> value1 </childNode>
<childNode> value2 </childNode>
...
<childNode> valueN </childNode>
</parentNode>
The name of child node is not going to change.
Parent node is not a root node.
Can someone please help me figure out what am I missing.
Thanks.
I checked this for you, it looks like it is working as expected to me. What you have perhaps missed is that the changes to your xml are happening in memory? This is what I've done:
input xml file
<rootNode>
<parentNode></parentNode>
</rootNode>
java test class
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class DocBuilderTest {
private String filePath = "src/test/resource/doc.xml";
#Test
public void builder()
throws ParserConfigurationException, IOException, SAXException, TransformerException {
System.out.println(processFile("parentNode", "value", "childNode"));
}
private String processFile(String parentNode, String value, String childNode)
throws ParserConfigurationException, SAXException, IOException, TransformerException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filePath);
Node pNode = doc.getElementsByTagName(parentNode).item(0);
for (int i = 0; i < 5; i++) {
String nodeValue = value + i;
Element newNode = doc.createElement(childNode);
newNode.appendChild(doc.createTextNode(nodeValue));
pNode.appendChild(newNode);
}
return toPrettyPrintString(doc);
}
// From https://stackoverflow.com/a/139096/7421645
private String toPrettyPrintString(Document doc) throws TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
return result.getWriter().toString();
}
}
The pretty print reference if the file is already partially indented.
and output to System.out
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<rootNode>
<parentNode>
<childNode>value0</childNode>
<childNode>value1</childNode>
<childNode>value2</childNode>
<childNode>value3</childNode>
<childNode>value4</childNode>
</parentNode>
</rootNode>
NOTE This output is just printed to System.out, I've not overwritten the input file. You'd need to initialise a FileWriter to do that.
How to create a xml file and save it in some place in my machine using java..there are attributes also include in the xml file? I have found org.w3c.dom.Document but having problems with creating attributes for elements and save the xml file.
Thank You.
You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
//staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
//set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
//shorten way
//staff.setAttribute("id", "1");
//firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
//lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
//nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
//salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\testing.xml"));
transformer.transform(source, result);
System.out.println("Done");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException tfe){
tfe.printStackTrace();
}
You can use Xembly, a small open source library that makes this XML creating process much more intuitive:
String xml = new Xembler(
new Directives()
.add("root")
.add("order")
.attr("id", "553")
.set("$140.00")
).xml();
Xembly is a wrapper around native Java DOM, and is a very lightweight library (I'm the author).
Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you'll find a lot of examples and snippets.
dom4j - Quick start guide
Just happened to work at this also, use https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm the example from here, and read the explanations. Also I provide you my own example:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("words");
doc.appendChild(rootElement);
while (ptbt.hasNext()) {
CoreLabel label = ptbt.next();
System.out.println(label);
m = r1.matcher(label.toString());
//System.out.println(m.find());
if (m.find() == true) {
Element w = doc.createElement("word");
w.appendChild(doc.createTextNode(label.toString()));
rootElement.appendChild(w);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml"));
transformer.transform(source, result);
// Output to console for testing
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements.
The output is: Billbuyedapples (I've read the sentence from a file)
I am providing an answer from my own blog. Hope this will help.
What will be output?
Following XML file named users.xml will be created.
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<users>
<user uid="1">
<firstname>Interview</firstname>
<lastname>Bubble</lastname>
<email>admin#interviewBubble.com</email>
</user>
</users>
PROCEDURE
Basic steps, in order to create an XML File with a DOM Parser, are:
Create a DocumentBuilder instance.
Create a Document from the above DocumentBuilder.
Create the elements you want using the Element class and its appendChild method.
Create a new Transformer instance and a new DOMSource instance.
Create a new StreamResult to the output stream you want to use.
Use transform method to write the DOM object to the output stream.
SOURCE CODE:
package com.example.TestApp;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;
public class CreateXMLFileJava {
public static void main(String[] args) throws ParserConfigurationException,
IOException,
TransformerException
{
// 1.Create a DocumentBuilder instance
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuilder = dbFactory.newDocumentBuilder();
// 2. Create a Document from the above DocumentBuilder.
Document document = dbuilder.newDocument();
// 3. Create the elements you want using the Element class and its appendChild method.
// root element
Element users = document.createElement("users");
document.appendChild(users);
// child element
Element user = document.createElement("user");
users.appendChild(user);
// Attribute of child element
user.setAttribute("uid", "1");
// firstname Element
Element firstName = document.createElement("firstName");
firstName.appendChild(document.createTextNode("Interview"));
user.appendChild(firstName);
// lastName element
Element lastName = document.createElement("lastName");
lastName.appendChild(document.createTextNode("Bubble"));
user.appendChild(lastName);
// email element
Element email = document.createElement("email");
email.appendChild(document.createTextNode("admin#interviewBubble.com"));
user.appendChild(email);
// write content into xml file
// 4. Create a new Transformer instance and a new DOMSource instance.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
// 5. Create a new StreamResult to the output stream you want to use.
StreamResult result = new StreamResult(new File("/Users/admin/Desktop/users.xml"));
// StreamResult result = new StreamResult(System.out); // to print on console
// 6. Use transform method to write the DOM object to the output stream.
transformer.transform(source, result);
System.out.println("File created successfully");
}
}
OUTPUT:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<users>
<user uid="1">
<firstName>Interview</firstName>
<lastName>Bubble</lastName>
<email>admin#interviewBubble.com</email>
</user>
</users>
You might want to give XStream a shot, it is not complicated. It basically does the heavy lifting.
I liked the Xembly syntax, but it is not a statically typed API. You can get this with XMLBeam:
// Declare a projection
public interface Projection {
#XBWrite("/root/order/#id")
Projection setID(int id);
#XBWrite("/root/order")
Projection setValue(String value);
}
public static void main(String[] args) {
// create a projector
XBProjector projector = new XBProjector();
// use it to create a projection instance
Projection projection = projector.projectEmptyDocument(Projection.class);
// You get a fluent API, with java types in parameters
projection.setID(553).setValue("$140.00");
// Use the projector again to do IO stuff or create an XML-string
projector.toXMLString(projection);
}
My experience is that this works great even when the XML gets more complicated. You can just decouple the XML structure from your java code structure.
package com.server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.w3c.dom.*;
import com.gwtext.client.data.XmlReader;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class XmlServlet extends HttpServlet
{
NodeList list;
Connection con=null;
Statement st=null;
ResultSet rs = null;
String xmlString ;
BufferedWriter bw;
String displayTo;
String displayFrom;
String addressto;
String addressFrom;
Date send;
String Subject;
String body;
String category;
Document doc1;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
System.out.print("on server");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
System.out.print("on server");
try
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
//creating a new instance of a DOM to build a DOM tree.
doc1 = docBuilder.newDocument();
new XmlServlet().createXmlTree(doc1);
System.out.print("on server");
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public void createXmlTree(Document doc) throws Exception {
//This method creates an element node
System.out.println("ruchipaliwal111");
try
{
System.out.println("ruchi111");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
st = con.createStatement();
rs = st.executeQuery("select * from data");
Element root = doc.createElement("message");
doc.appendChild(root);
while(rs.next())
{
displayTo=rs.getString(1).toString();
System.out.println(displayTo+"getdataname");
displayFrom=rs.getString(2).toString();
System.out.println(displayFrom +"getdataname");
addressto=rs.getString(3).toString();
System.out.println(addressto +"getdataname");
addressFrom=rs.getString(4).toString();
System.out.println(addressFrom +"getdataname");
send=rs.getDate(5);
System.out.println(send +"getdataname");
Subject=rs.getString(6).toString();
System.out.println(Subject +"getdataname");
body=rs.getString(7).toString();
System.out.println(body+"getdataname");
category=rs.getString(8).toString();
System.out.println(category +"getdataname");
//adding a node after the last child node of ssthe specified node.
Element element1 = doc.createElement("Header");
root.appendChild(element1);
Element child1 = doc.createElement("To");
element1.appendChild(child1);
child1.setAttribute("displayNameTo",displayTo);
child1.setAttribute("addressTo",addressto);
Element child2 = doc.createElement("From");
element1.appendChild(child2);
child2.setAttribute("displayNameFrom",displayFrom);
child2.setAttribute("addressFrom",addressFrom);
Element child3 = doc.createElement("Send");
element1.appendChild(child3);
Text text2 = doc.createTextNode(send.toString());
child3.appendChild(text2);
Element child4 = doc.createElement("Subject");
element1.appendChild(child4);
Text text3 = doc.createTextNode(Subject);
child4.appendChild(text3);
Element child5 = doc.createElement("category");
element1.appendChild(child5);
Text text44 = doc.createTextNode(category);
child5.appendChild(text44);
Element element2 = doc.createElement("Body");
root.appendChild(element2);
Text text1 = doc.createTextNode(body);
element2.appendChild(text1);
/*
Element child1 = doc.createElement("name");
root.appendChild(child1);
Text text = doc.createTextNode(getdataname);
child1.appendChild(text);
Element element = doc.createElement("address");
root.appendChild(element);
Text text1 = doc.createTextNode( getdataaddress);
element.appendChild(text1);
*/
}
//TransformerFactory instance is used to create Transformer objects.
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
xmlString = sw.toString();
File file = new File("./war/ds/newxml.xml");
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(xmlString);
}
catch(Exception e)
{
System.out.print("after while loop exception"+e.toString());
}
bw.flush();
bw.close();
System.out.println("successfully done.....");
}
}
I want to append an attribute an existing element in XML using Java. For example:
<employee>
<details name="Jai" age="25"/>
<details name="kishore" age="30"/>
</employee>
It want to add weight to it (assume that it is calculated and then appended in response). How can I append that to all items?
<details name="Jai" age="25" weight="55"/>
import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class AddAndPrint {
public static void main(String[] args) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");
NodeList employees = document.getElementsByTagName("employee");
for (Node employee : employees) {
for (Node child : employee.getChildNodes() {
if ("details".equals(child.getNodeName()) child.setAttribute("weight", "150");
}
}
try {
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
System.out.println(stringWriter.getBuffer().toString());
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
Here is a quick solution based on jdom:
public static void main(String[] args) throws JDOMException, IOException {
File xmlFile = new File("employee.xml");
SAXBuilder builder = new SAXBuilder();
Document build = builder.build(xmlFile);
XPath details = XPath.newInstance("//details");
List<Element> detailsNodes = details.selectNodes(build);
for (Element detailsNode:detailsNodes) {
detailsNode.setAttribute("weight", "70"); // static weight for demonstration
}
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(build, System.out);
}
First, we build a document (SAXBuilder), next we create a XPath expression for the details node, then we iterate through the elements for that expression and add the weight attribute.
The last two lines just verify that it's white magic :-)