DOM

Add attribute in DOM element

Photo of Byron KiourtzoglouByron KiourtzoglouNovember 11th, 2012Last Updated: July 6th, 2013
1 1,150 2 minutes read

This is an example of how to add an attribute in a DOM element.We have implemented a method, that isvoid prettyPrint(Document xml), in order to convert a DOM into a formatted XML String. Adding an attribute in a DOM element implies that you should:

  • Obtain a new instance of aDocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
  • Set the parser produced so as not to validate documents as they are parsed, usingsetValidating(boolean validating) API method of DocumentBuilderFactory, with validating set to false.
  • Create a new instance of aDocumentBuilder, usingnewDocumentBuilder() API method of DocumentBuilderFactory.
  • Parse theFileInputStream with the content to be parsed, usingparse(InputStream is) API method of DocumentBuilder. This method parses the content of the given InputStream as an XML document and returns a new DOMDocument object.
  • Get theNodeList of all theElement objects in document order with a given tag name and are contained in the document usinggetElementsByTagName(String tagname) API method ofDocument and from this nodeList get the first element.
  • Add a new attribute to the element, usingsetAttribute(String name, String value).
  • Callvoid prettyPrint(Document xml) method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding. The method uses aTransformer, that is created usingnewTransformer() API method ofTransformerFactory. The Transformer is used to transform a source tree into a result tree. After setting specific output properties to the transformer, usingsetOutputProperty(String name, String value) API method of Transformer, the method uses it to make the transformation, withtransform(Source xmlSource, Result outputTarget) API method of Transformer. The parameters are theDOMSource with the DOM node and the result that is aStreamResult created from aStringWriter.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;import java.io.File;import java.io.FileInputStream;import java.io.StringWriter;import java.io.Writer;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;public class AddAttributeInDOMElement {public static void main(String[] args) throws Exception {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();dbf.setValidating(false);DocumentBuilder db = dbf.newDocumentBuilder();Document doc = db.parse(new FileInputStream(new File("in.xml")));Element element = (Element) doc.getElementsByTagName("channel").item(0);// Adds a new attribute. If an attribute with that name is already present     // in the element, its value is changed to be that of the value parameterelement.setAttribute("newattr", "attrvalue");prettyPrint(doc);// whether an attribute with a given name is specified on this element or has a default valueboolean hasAttribute = element.hasAttribute("newattr");System.out.println("Attribute Added: " + hasAttribute);}public static final void prettyPrint(Document xml) throws Exception {Transformer tf = TransformerFactory.newInstance().newTransformer();tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");tf.setOutputProperty(OutputKeys.INDENT, "yes");Writer out = new StringWriter();tf.transform(new DOMSource(xml), new StreamResult(out));System.out.println(out.toString());}}

Input:

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>Java Tutorials and Examples</title><item><title><![CDATA[Java Tutorials]]></title><link>http://www.javacodegeeks.com/</link></item><item><title><![CDATA[Java Examples]]></title><link>http://examples.javacodegeeks.com/</link></item></channel></rss>

Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss version="2.0"><channel newattr="attrvalue"><title>Java Tutorials and Examples</title><item><title><![CDATA[Java Tutorials]]></title><link>http://www.javacodegeeks.com/</link></item><item><title><![CDATA[Java Examples]]></title><link>http://examples.javacodegeeks.com/</link></item></channel></rss>Attribute Added: true

 
This was an example of how to add an attribute in a DOM element in Java.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Byron KiourtzoglouByron KiourtzoglouNovember 11th, 2012Last Updated: July 6th, 2013
1 1,150 2 minutes read
Photo of Byron Kiourtzoglou

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor atJava Code Geeks.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.