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

 
 

JDOM Attribute Example, How to add a list of attribute at a xml file element.
Posted on: August 20, 2010 at 12:00 AM
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

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


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.