Home Tutorial Xml Jdom JDOM Attribute Example, How to add a list of attribute at a xml file element.

 
 

Share on Google+Share on Google+
JDOM Attribute Example, How to add a list of attribute at a xml file element.
Posted on: August 20, 2010 at 12:00 AM
Advertisement
In this tutorial, you will see how to add a list of attribute at a xml file element.

JDOM Attribute Example, How to add a list of attribute to a xml file

In this tutorial, we will see how to add a list of attribute to a xml file element with the help
of JDOM library.

With the help of this java code, you can add a list of attribute. By using Attrribute class we
will create number of  attribute, which we want to add to xml element. The add() method of
ArrayList add attribute in ArrayList. The setAttribute(java.utill.ArryList  newAttr) of
Element class add attribute list at xml element.

Code:

book.xml

<?xml version="1.0" encoding="UTF-8"?>
<BookCatalog>
  <book>
        <name>Java</name>
        <year>2000</year>
  </book>
   <book>
         <name>c</name>
         <year>1986</year>
  </book>
</BookCatalog>

AddAttributeList.java

package roseindia;

import java.io.File;
import java.util.ArrayList;
import org.jdom.input.DOMBuilder;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class AddAttributeList {
  public static void main(String[] args) {
    DOMBuilder docbuilder = new DOMBuilder();
    File file = new File("book.xml");
    try {
      Document doc = docbuilder.build(file);
      Element rootElement = doc.getRootElement();
      Attribute id = new Attribute("id""22");
      Attribute auther = new Attribute("Auther""xyz");
      Attribute type = new Attribute("type""program");
      ArrayList a = new ArrayList();
      a.add(id);
      a.add(auther);
      a.add(type);
      rootElement.getChild("book").setAttributes(a);
      XMLOutputter output = new XMLOutputter();
System.out.println("After adding attribute list in xml file.");
      output.output(doc, System.out);
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

After adding attribute list in xml file.
<?xml version="1.0" encoding="UTF-8"?>
<BookCatalog>
   <book id="22" Auther="xyz" type="program">
                   <name>Java</name>

                   <year>2000</year>
        
< /book> 
          <book>
 
                 <name>c</name>
               <year>1986</year>
 </book>
 </BookCatalog>

Download this code

Advertisement

Related Tags for JDOM Attribute Example, How to add a list of attribute at a xml file element.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 20, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com