traversing xml document using SAX parser and printing output in desired format

时间:2016-03-02 11:01:41

标签: java xml sax

I am trying to parse attached xml(Please find attachment) file. xml document is as given below.check the attachment 1 and 2

sample data of xml filesample data of xml file

In order to parse this xml, I used SAX parser. program is as follows.

package com.dom;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public class DemoXML {
    File file;
    SAXParserFactory factory;
    SAXParser saxParser;
    UserHandler handler;

    public void loadXML()
    {
        file = new File("E:/fifthWorkbenchProjects/XMLUtility/src/input/FIXBOND.xml");
        System.out.println(file.exists());
    }
    public void readXML()
    {
        factory = SAXParserFactory.newInstance();

            try {
                saxParser = factory.newSAXParser();
                handler = new UserHandler();
                try {
                    saxParser.parse(file,handler);
                } catch (IOException e) {

                    e.printStackTrace();
                }


            } catch (ParserConfigurationException e) {

                e.printStackTrace();
            } catch (SAXException e) {

                e.printStackTrace();
            }


    }
public static void main(String args[])
{
    DemoXML ob = new DemoXML();
    ob.loadXML();
    ob.readXML();
}
}

 class UserHandler extends DefaultHandler
{
     Hashtable tags;
     @Override
    public void startDocument()
    {
        System.out.println("Document started");
        tags = new Hashtable();
    }
     @Override
     public void endDocument()
     {
         System.out.println("Documents ended"); 
     }

     @Override
     public void startElement(String namespaceURI,String localName,String qname,Attributes atts) throws SAXException
     {
        // System.out.println("Element started");
        // if(qname.equals("Currency"))
        System.out.print(qname+"-->");

     }

     @Override
     public void endElement(String uri,String localName, String qname)
     {

     }
     @Override
     public void characters(char[] ch, int start, int length)
     {
         String str =  new String(ch,start,length);
         System.out.println(str);
         System.out.println();
     }

}

I get output in following manner. true Document started FIgovcorpagncy-->InstrumentDescription-->InstrumentType-->FI GOVCORPAGNCY

InstrumentSubType-->FIXDBOND

InstrumentName-->QUEENSNR 0% 07/06/2016

InstrumentDescription-->QUEENSNR 0% 07/06/2016

Currency-->GBP

InstrumentStatus-->ACTIVE

AmountOutstanding-->48384375

AmtOutstandingDate-->2012-06-27T00:00:00.000

PrincipalExchange-->N

CountryOfRisk-->GB

InstrumentCompleteness-->50

CapitalRanking-->1

AtIssuance-->IssueDate-->2012-06-27T00:00:00.000

OriginalIssueAmount-->48384375

PrivatePlacementFlag-->Y

MinimumDenomination-->1000

MinimumIncrement-->0.01

and so on ....I am able to access all nodes but observe one thing over here for first element in tree,complete element address is printed like FIgovcorpagncy-->InstrumentDescription-->InstrumentType-->FI GOVCORPAGNCY

then for rest of the elements in tree, it prints tag name and corresponding value like InstrumentSubType-->FIXDBOND

InstrumentName-->QUEENSNR 0% 07/06/2016

InstrumentDescription-->QUEENSNR 0% 07/06/2016

Currency-->GBP

InstrumentStatus-->ACTIVE

AmountOutstanding-->48384375

so on....

here my requirement is I want to print these elements also with full hierarchic manner as the first element.

how to go about it?

1 个答案:

答案 0 :(得分:1)

类UserHandler扩展了DefaultHandler {      列出li_elements,li_values;

 LinkedHashMap<List<String>,List<String>> hm; 
 boolean endElementFlag;

 @Override
public void startDocument()
{
    System.out.println("Document started");
    li_elements = new ArrayList<String>();
    li_values=new ArrayList<String>();
}
 @Override
 public void endDocument()
 {
     System.out.println("Documents ended"+hm.size()); 
     for(Map.Entry m:hm.entrySet())
     {
         System.out.println(m.getKey()+""+m.getValue());
     }

 }

 @Override
 public void startElement(String namespaceURI,String localName,String qname,Attributes atts) throws SAXException
 {

    li_elements.add(qname);

    //System.out.println("Element Started");
    //System.out.println(qname+" added in element list");   
 }
 @Override
 public void endElement(String uri,String localName, String qname)
 {

     if(!li_values.isEmpty())
     {
     System.out.println("Element address list:-"+li_elements+"and Corresponding Value:-"+li_values);

     System.out.println();
     }

         li_elements.remove(li_elements.size()-1);
         li_values.clear();

 }
 @Override
 public void characters(char[] ch, int start, int length)
 {

    String str =  new String(ch,start,length);
    li_values.add(str);
 }  

}

我期待这样的事情。这会以我希望的格式打印输出。