Get attribute value using XML Stream Reader in Java

Description

The following code shows how to get attribute value using XML Stream Reader.

Example


import java.io.StringReader;
/*from w w w.ja v a2 s . co m*/
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class Main{
   public static void main(String[] args) throws Exception{
      StringReader sr = new StringReader("<tag src='java2s.com'></tag>");
      XMLInputFactory factory = XMLInputFactory.newInstance();
      XMLStreamReader parser = factory.createXMLStreamReader(sr);
      while (parser.hasNext()){
         int event = parser.next();
         if (event == XMLStreamConstants.START_ELEMENT){
            if (parser.getLocalName().equals("tag")){
               String href = parser.getAttributeValue(null, "src");
               if (href != null)
                  System.out.println(href);               
            }
         }
      }
   }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    XML »




DOM
SAX