tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 XML > XOM > Add Attribute

Add Attribute 

XOM (XML Object Model) is a tree based java API for processing XML by taking the best ideas from SAX and DOM. It is simple, fast and easy to use. This requires the library xom-1.2.7.jar to be in classpath. The following example shows adding an attribute to a specific element.

File Name  :  
com/bethecoder/tutorials/xom/tests/AddAttribute.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.xom.tests;

import java.io.IOException;
import java.util.Random;

import nu.xom.Attribute;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;

public class AddAttribute {

  /**
   @param args
   @throws IOException 
   */
  public static void main(String[] argsthrows IOException {
    Document doc = new Document(new Element("RandomNumbers"));
    
    Random random = new Random();
    int randNum;
    Element ranEle = null;
    Attribute attribute = null;
    
    for (int i = ; i < 10 ; i ++) {
      randNum = random.nextInt(1729);
      //Create a new attribute with boolean string as value
      attribute = new Attribute("even", String.valueOf(randNum % == 0));
      
      ranEle = new Element("Number");
      ranEle.appendChild(String.valueOf(randNum));
      ranEle.addAttribute(attribute)//Add the new attribute
      
      //Append the newly created child element
      doc.getRootElement().appendChild(ranEle);
    }
    
    //Pretty print
    Serializer serializer = new Serializer(System.out, "UTF-8");
    serializer.setIndent(4);
    serializer.write(doc);
    serializer.flush();
  }

}
   

It gives the following output,
File Name  :  OUTPUT



 
  


  
bl  br