How to create XML file with specific structure in Java [duplicate] - java

This question already has answers here:
Save XML format to a string instead of a file [duplicate]
(2 answers)
How to read and write XML files?
(6 answers)
Create XML file using java
(8 answers)
Closed 5 years ago.
I would like to create XML file using Java.
My XML file structure:
<?xml version="1.0" encoding="UTF-8"?>
<CONFIGURATION>
<BROWSER>chrome</BROWSER>
<BASE>http:fut</BASE>
<ENVIRONMENT>abcd</ENVIRONMENT>
<USER>john</USER>
<PASSWORD>abcd123</PASSWORD>
<ORGANIZATION>Tim</ORGANIZATION>
<EMPLOYEE>
<EMP_NAME>Anhorn, Irene</EMP_NAME>
<ACT_DATE>20131201</ACT_DATE>
<DATE_IN>20131201</DATE_IN>
<CLOCK_IN>0800</CLOCK_IN>
<DATE_OUT>20131201</DATE_OUT>
<CLOCK_OUT>1600</CLOCK_OUT>
</EMPLOYEE>
<EMPLOYEE>
<EMP_NAME>Arlegui, Karen Jay</EMP_NAME>
<ACT_DATE>20131201</ACT_DATE>
<DATE_IN>20131201</DATE_IN>
<CLOCK_IN>1600</CLOCK_IN>
<DATE_OUT>20131202</DATE_OUT>
<CLOCK_OUT>0000</CLOCK_OUT>
</EMPLOYEE>
</CONFIGURATION>

You can use the JDOM library in Java.
Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:
//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));

public static void main(String[] args) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("CONFIGURATION");
doc.appendChild(rootElement);
Element browser = doc.createElement("BROWSER");
browser.appendChild(doc.createTextNode("chrome"));
rootElement.appendChild(browser);
Element base = doc.createElement("BASE");
base.appendChild(doc.createTextNode("http:fut"));
rootElement.appendChild(base);
Element employee = doc.createElement("EMPLOYEE");
rootElement.appendChild(employee);
Element empName = doc.createElement("EMP_NAME");
empName.appendChild(doc.createTextNode("Anhorn, Irene"));
employee.appendChild(empName);
Element actDate = doc.createElement("ACT_DATE");
actDate.appendChild(doc.createTextNode("20131201"));
employee.appendChild(actDate);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/Users/myXml/ScoreDetail.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();}}
The values in you XML is Hard coded.

Use JAXB:
http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
package com.mkyong.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}

There is no need for any External libraries, the JRE System libraries provide all you need.
I am infering that you have a org.w3c.dom.Document object you would like to write to a file
To do that, you use a javax.xml.transform.Transformer:
import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLWriter {
public static void writeDocumentToFile(Document document, File file) {
// Make a transformer factory to create the Transformer
TransformerFactory tFactory = TransformerFactory.newInstance();
// Make the Transformer
Transformer transformer = tFactory.newTransformer();
// Mark the document as a DOM (XML) source
DOMSource source = new DOMSource(document);
// Say where we want the XML to go
StreamResult result = new StreamResult(file);
// Write the XML to file
transformer.transform(source, result);
}
}
Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

Related

force removeAttribute() from org.w3c.dom.Element

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

Java DocumentBuilder - wrong indentation in XML file

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.

XML Utility class exist for simple modification - add, remove/delete, change/modify?

Does a Java library exist that has the capability shown in the client code below? I'm looking for a library that provides basic XML manipulation capabilities using strings.
MagicXml mXml = MagicXmlUtil.createXml("<team name='cougars'><players><player name='Michael'/></players></team>");
mXml.addNode("players", "<player name='Frank'/>");
mXml.addNode("players", "<player name='Delete Me'/>");
mXml.removeNode("player[#name='Delete Me']");
mXml.addAttribute("team[#name='cougars']", "city", "New York");
mXml.addAttribute("team[#name='cougars']", "deleteMeAttribute", "Delete Me");
mXml.removeAttribute("team[#name='cougars']", "deleteMeAttribute");
mXml.modifyAttribute("player[#name='Michael']", "name", "Mike");
mXml.setNodeValue("player[#name='Mike']", "node value for Mike");
MagicXmlNode node = mXml.getNode("<player[#name='Frank'/>");
mXml.addNode("players", node);
mXml.modifyAttribute("player[#name='Frank'][1]", "name", "Frank2");
System.out.println("mXml:\n" + mXml.toString());
mXml:
<team name='cougars' city="New York">
<players>
<player name='Mike'>
node value for Mike
</player>
<player name='Frank' />
<player name='Frank2' />
</players>
</team>
there are many different java libraries for xml manipulation/editing, the basics one with java standard library are hard to use if your a beginner so you should try JDOM(java document object model) for parsing and editing is easy.
Read a bit of documentation and download sample code here if you want to try http://www.jdom.org/ good luck =)
Whether you use something already existing like dom4j or jdom or as I said in my comment you create a simple class that wraps call to finding nodes using XPath and adding/removing what you want (Nodes, Attributes etc).
This is a sample class, I'll let you add what's missing (modifyAttribute, setNodeValue etc)
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class MagicXml {
static XPath xpath = XPathFactory.newInstance().newXPath();
Document doc;
Element root;
public MagicXml(String xml) throws Exception {
doc = parseXml(xml);
root = doc.getDocumentElement();
}
private static Document parseXml(String xml) throws Exception {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
return docBuilder.parse(bis);
}
private String asXPath(String path) {
return path.startsWith("/") ? path : "//" + path;
}
private static Node findNode(Document doc, String xPath) throws Exception {
XPathExpression expr = xpath.compile(xPath);
return (Node) expr.evaluate(doc, XPathConstants.NODE);
}
public static MagicXml createXml(String xml) throws Exception {
return new MagicXml(xml);
}
public MagicXml addNode(String path, String xml) throws Exception {
Document subDoc = parseXml(xml);
Node destNode = findNode(doc, asXPath(path));
Node srcNode = subDoc.getFirstChild();
destNode.appendChild(doc.adoptNode(srcNode.cloneNode(true)));
return this;
}
public MagicXml removeNode(String path) throws Exception {
Node destNode = findNode(doc, asXPath(path));
destNode.getParentNode().removeChild(destNode);
return this;
}
public MagicXml addAttribute(String path, String attr, String value) throws Exception {
Element destNode = (Element)findNode(doc, asXPath(path));
destNode.setAttribute(attr, value);
return this;
}
public MagicXml removeAttribute(String path, String attr) throws Exception {
Element destNode = (Element)findNode(doc, asXPath(path));
destNode.removeAttribute(attr);
return this;
}
public String docToString(Document doc) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception e) {
return "";
}
}
public String toString() {
return docToString(doc);
}
public static void main(String[] args) throws Exception {
System.out.println(//
MagicXml.createXml("<team name='cougars'><players><player name='Michael'/></players></team>")//
.addNode("players", "<player name='Frank'/>")//
.addNode("players", "<player name='Delete Me'/>")//
.removeNode("player[#name='Delete Me']") //
.addAttribute("player[#name='Frank']", "foo", "bar") //
.addAttribute("player[#name='Frank']", "bar", "bazz") //
.removeAttribute("player[#name='Frank']", "bar") //
.toString());
}
}
XStream is a very easy XML manipulation tool. It can go from java classes to XML and vice versa very easily.

Create XML file using java

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.....");
}
}

How can I append an attribute to an existing XML element in Java?

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

Categories

Resources