Trying to parse a huge XML file

I'm trying to parse a large (~200 Meg) XML file. I get out of memory errors with DOM, and so far using SAX has been a huge disaster. My program has to run on IE and Netscape as an applet. I've run into a HUGE amount of errors. While I have been doing Java programming for about 2 years, this is the first time I've ever worked with XML. The error I am currently getting is an abstract method error associated with the following code :
SAXParserFactory spf = new
                         com.sun.xml.parser.SAXParserFactoryImpl();
               spf.setValidating(false);
               try {
               out.write("Gets past SAXParserFactory creation");
               out.flush();
                    catch (Exception e) {}
               xmlReader = null;
               try {
                         // Create a JAXP SAXParser
                         saxParser = spf.newSAXParser();
                         // Get the encapsulated SAX XMLReader
                         out.write("gets to assigning an XMLReader");
***THIS LINE OF CODE ***                         xmlReader = saxParser.getXMLReader();
                         out.write("gets past assigning an XMLReader");
                         out.flush();
I've run out of ideas and would greatly appreciate any help anyone could offer on this most frustrating problem.

With XML, we don't have to check each line of the file, only the data in those tags of each element that we are searching on.That's true, once you have read the entire XML and parsed it. Reading the entire XML would of course take much longer than reading the text file it was generated from, so you would want to pre-parse it into a DOM and store that somehow. But then to do a search you'd have to load that DOM, which is in turn much larger than the XML it was generated from...
What you describe sounds to me a lot like a database application. Of course I don't know anything about the specifics of what you are doing with the text, but storing it in a database with indexes that support the searches seems to me like a better approach. Of course you then have the challenge of distributing the database and its supporting software in a form that doesn't require installation. But I'd respectfully suggest that banning any installation at all is a bit extreme. After all, where I live you can buy an encyclopedia on a CD, from a gas station, for $10. And when you load the CD, it runs through an installation procedure. No big deal these days.

Similar Messages

  • Non-blocking parsing of multiple xml files

    Hi there,
    I'm trying to parse multiple huge XML files concurrently for a query system over multiple xml streaming systems.
    For each huge xml file, I read them into the memory gradually (the new data would cover the old data in the buffer if the buffer is full). Two questions here:
    1. Do I have to set up a socket and write the buffered data to the socket in order to simuate that the parser can parse infinitely? It sounds not good to use socket across two threads just for the "infinite" nature.
    2. I want to simulate concurrently parsing multiple streams. A straightforward way is to have each parser sit in a thread. Is there any otherway that I can put all parsers in one thread and alternately call them? This requires that each individual parser could parse whatever they have seen so far rather and resume when they are called again.
    I'm curiously awaiting for your answers.
    thanks a lot,
    hong

    just taking a guess: create your own reader by extending java.io.Reader ; and let this reader taking care of fetching the data that the parser will use.

  • JAXB parsing an incomplete xml file

    hi folks,
    i am trying to parse a incomplete xml file (e.g some attribute and child elements are missing) in order to complete it via jaxb. however, parsing throws a SAXParseException (premature end of file), which interally is marked as unrecoverable, and a unmarshaller isn't capable of returning a result. not even the objects created so far.
    so my question is if there a way of getting the (incomplete) object tree no matter if the parsing was successfully or not. (i am aware of the fact, that this object tree might be invalid)
    cheer, johannes

    Thanks, works like a charm :)
    Another question.
    I have an index.jsp page with an HTML form (a simple "search" form, made of a text area and a submit button). Now, what I want to do is passing the parameter to two distinct servlets, each one dealing with a web service (one with ebay, the other one with last.fm).
    Unfortunately, in the action tag of the form only one value can be specified.
    Any suggestions?

  • Reading  huge xml files in OSB11gR1(11.1.1.6.0)

    Hi,
    I want to read a huge xml file of size 1GB in OSB(11.1.1.6.0)?
    I will be creating a (JCA)file adapter in jdeveloper and importing artifacts to OSB.
    Please let me know the maximum file size that could be handled in OSB?
    Thanks in advance.
    Regards,
    Suresh

    Depends on what you intend to do after reading the file.
    Do you want to parse the file contents and may be do some transformation? Or do you just have to move the file from one place to another for ex. reading from local system and moving to a remote system using FTP?
    If you just have to move the file, I would suggest using JCA File/FTP adapter's Move operation.
    If you have to parse and process the file contents within OSB, then it may be possible depending on the file type and what logic you need to implement. For ex. for very large CSV files you can use JCA File Adapter batching to read a few records at a time.

  • Sax Parser for loading XML file

    We have a requirment by which we need to load huge XMl file in our DB everyday.
    THe XML file format is like --
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    <dept>
    <name>productiong</name>
    <location>USA</location>
    <dept>
    I have written XMl SAX parser to load this file into DB -
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.Attributes;
    import java.io.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import oracle.jdbc.pool.OracleDataSource;
    import java.util.*;
    public class test extends DefaultHandler
    String thisElement="";
    String table_name="";
    String table_name_2="";
    String sql="";
    String value_clause="";
    StringBuffer value_clauseBuffer;
    String Insert_sql="";
    int flag;
    String columnNames="";
    String questionmarks="";
    static String conStr = "jdbc:oracle:thin:@abcd1234:1521:dss501";
    static Connection conn;
    String arrayValues[] = new String[30];
    int j = 0;
    int emptyElementFlag = 0;
    public SurveyReader() throws SQLException, FileNotFoundException, IOException{
    DBConnect("username", "password");
    public static void DBConnect(String username, String password)
    throws SQLException, FileNotFoundException, IOException {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(conStr, username, password);
    conn.setAutoCommit(true);
    public void startElement(String namespaceURI, String localName,
    String qName, Attributes atts) throws SAXException {
    thisElement = qName;
    if (thisElement!=table_name){
    columnNames = columnNames + ", " + qName;
    questionmarks = questionmarks +", " + "?";
    emptyElementFlag =0;
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    if (thisElement !="root"){     
    if ((length == 0) && (thisElement !="") ){
    table_name = thisElement;
    sql = " Insert into "+ table_name +"(";
    value_clause="";
    value_clauseBuffer =null;
    columnNames = "";
    questionmarks ="";
    j =0;
    if ((length != 0) && (thisElement!="") && (thisElement!=table_name)){
    emptyElementFlag = 1;
    String s = new String(ch, start, length);
    String newString = s.replaceAll("'", "''");
    // String newString = s;
    if (value_clauseBuffer== null){
    value_clauseBuffer = new StringBuffer(newString);
    else{
    value_clauseBuffer.append(newString);
    public void endElement(String namespaceURI, String localName, String qName)
    throws SAXException {
    if (thisElement !="root"){
    if ((!(value_clauseBuffer == null))||((emptyElementFlag ==0) && (qName !=table_name))) {
    try{
    //value_clauseBuffer.append("', '");
    if (value_clauseBuffer == null){
    arrayValues[j]="";
    else{
    arrayValues[j]=""+value_clauseBuffer;
    j = j+1;
    value_clauseBuffer = null;
    emptyElementFlag =0;
    }catch(Exception e){
    System.err.println(e);
    System.exit(2);
    if (qName == table_name){
    if (!(value_clauseBuffer == null)){
    value_clause = "'"+value_clauseBuffer;
    columnNames =columnNames.substring(1, columnNames.length());
    int paramNumber = j;
    questionmarks =questionmarks.substring(1, questionmarks.length());
    sql = sql + columnNames + " ) values (" + questionmarks +"); ";
    Insert_sql=Insert_sql + sql;
    sql = "Begin "+sql + " End; ";
         try{
         PreparedStatement pstat = conn.prepareStatement(sql);
    for (int i=0; i<=j-1; i++ ){
    int k = i+1;
    pstat.setObject(k, arrayValues);
         ResultSet rset = pstat.executeQuery();
         rset.close();
         pstat.close();
    catch (Exception e) {
    System.err.println(e);
    System.out.print("sql " + sql);
    System.exit(1);
    table_name_2 = table_name;
    thisElement = "";
    public static void main (String args[]) {
    XMLReader xmlReader = null;
    System.out.println("Time " + new java.util.Date());
    try {
    SAXParserFactory spfactory = SAXParserFactory.newInstance();
    spfactory.setValidating(false);
    SAXParser saxParser = spfactory.newSAXParser();
    xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new SurveyReader());
    xmlReader.setErrorHandler(new SurveyReader());
    InputSource source = new InputSource("short.xml");
    xmlReader.parse(source);
    conn.close();
    } catch (Exception e) {
    System.err.println(e);
    System.exit(1);
    This parser takes 2 hours to laod file of size around 8MB.
    ANy suggestions on improving performance of the parser.
    ANy other approach I should be taking to load this file into DB.
    We are using ORacle 9i DB with Character set UTF 8.
    Thanks!

    String buf = (new String(ch, start, length)).trim();
    if (thisElement != "root"){   
    if ((buf.length() == 0) && (thisElement !="") ){
    It run ok!
    Thanks 58871!
    Now, i want to export oracle table to xml file like :
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    </root>
    Can SAX export to xml format?
    Pham Thanh Tung

  • Getting a iterator over a huge xml-file

    Hi !
    I have to persist data from some huge xml-files.
    The structure of the xml is simple, like in:
    <items>
    <item>
    </item>
    <item>
    </item>
    </items>
    The best way for me, is to get an iterator over the item-elements represented as a DOM strcture for easy access.
    Because the files are so huge (80-150 MBytes) and I have no control over the creation of them, the underlying parser should be SAX oriented.
    So I need a solution which will parse until one item-element (maybe spezified through a XPATH query) is completed and build a DOM-tree from it.
    Then I can pass this DOM-element to my persistence layer. When this item is persisted, and the Iterator hasNext(), then I could do a simple .next() to get the next DOM representation of the item.
    Is there such a solution out ? Or do I have to 'invent' such kind of parsing ?
    Would by great to get some hints ... this problem is driving me crazy :)
    Thank you in advance,
    Gerald

    Vaguely familiar, http://lists.xml.org/archives/xml-dev/200201/msg00032.html
    I can't think of a DOM builder that would work off a fragment; you would probably have to create one yourself.
    There's also http://drizzle.stanford.edu/~peastman/pax.html which might solve your problem.
    Pete

  • Reading huge XML file in ECC 6.0

    Hi ABAPexperts,
    Is there any way to read/parse a huge xml in ABAP (ECC 6.0)?
    I am looking at ixml and sxml, but ixml have memory issues and but is sxml available in ECC 6.0?
    Any example will help me.
    thank you for your help.

    Have you considered using Simple Transformation?
    It is should perform well on huge data due to linear processing.

  • How to parse contents from XML file in Java

    Hi All,
    I have a scenario like this . I have one xml file with key value pairs of ( name , URL ) . I have retrieved contents from XML file , now I want to parse these contents and store in a bean object.
    How to parse Contents of XML file??
    Thanks in advance,
    Rajendra.

    Hi All,
    I have a scenario like this . I have one xml file with key value pairs of ( name , URL ) . I have retrieved contents from XML file , now I want to parse these contents and store in a bean object.
    How to parse Contents of XML file??
    Thanks in advance,
    Rajendra.

  • How to break up a huge XML file and generate serialized JSP pages

    I have a huge xml file, with about 100 <item> nodes.
    I want to process this xml file with pagination and generate jsp pages.
    For example:
    Display items from 0 to 9 on page 1 page1.jsp , 10 to 19 on page2.jsp, and so on...
    Is it possible to generate JSP pages like this?
    I have heard of Velocity but dont know if it will be the right technology for this kind of a job.

    Thank you for your reply, I looked at the display tag library and it looks pretty neat with a lot of features, I could definitely use it in a different situation.
    The xml file size is about 1.35 MB, and the size is unpredictable it could shrink or grow periodically depending on the number of items available.
    I was hoping to create a documentation style (static pages) of the xml feed instead of having 1 jsp with dynamic pages
    I was looking at Anakia : http://jakarta.apache.org/velocity/docs/anakia.html , may be it has features that enable me to create static pages but not very sure.
    I think for now, I will transform the xml with an xsl file and pass the page numbers as input parameters to the xsl file
    null

  • How to compare two huge xml files(50MB+) using Java Code

    I want to compare two huge xml files using java code and need to find the difference of those xml files
    is there any API for that

    You should find third party API

  • Error parsing ERwin 7.x File when I  tried to IMPORT repository format xml file in SQl Data Modeller

    This is what i got in the log file when i tried to import a relatively large file 1.7 GB xml file
    Import Finished
    Errors:   1
    Warnings: 0
    <<<<< ERRORS >>>>>
    Error parsing ERwin 7.x File:<File path>
    Please help.

    The error information in the External log file is
    ERROR ERwinHandler - ERwinHandler - Unable to parse ERwin 7.x file: <file path>
    java.lang.OutOfMemoryError: Java heap space
      at oracle.dbtools.crest.model.ModelIDObject.<init>(ModelIDObject.java:46)
      at oracle.dbtools.crest.model.design.DesignObject.<init>(DesignObject.java:111)
      at oracle.dbtools.crest.model.design.ContainedObject.<init>(ContainedObject.java:82)
      at oracle.dbtools.crest.model.design.ContainedObjectWithDomain.<init>(ContainedObjectWithDomain.java:76)
      at oracle.dbtools.crest.model.design.relational.FKElement.<init>(FKElement.java:14)
      at oracle.dbtools.crest.model.design.relational.Column.<init>(Column.java:148)
      at oracle.dbtools.crest.model.design.relational.Table.createColumn(Table.java:432)
      at oracle.dbtools.crest.imports.erwin.ERSAXParserv7x.parseColumns(ERSAXParserv7x.java:1681)
      at oracle.dbtools.crest.imports.erwin.ERSAXParserv7x.parseEntity(ERSAXParserv7x.java:1364)
      at oracle.dbtools.crest.imports.erwin.ERSAXParserv7x.endEntitiesAndAttributes(ERSAXParserv7x.java:994)
      at oracle.dbtools.crest.imports.erwin.ERSAXParserv7x.endElement(ERSAXParserv7x.java:428)
      at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1666)
      at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:458)
      at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:404)
      at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:245)
      at oracle.xml.jaxp.JXSAXParser.parse(JXSAXParser.java:298)
      at oracle.dbtools.crest.imports.erwin.ERwinHandler.parseFile(ERwinHandler.java:252)
      at oracle.dbtools.crest.imports.erwin.ERwinHandler.access$500(ERwinHandler.java:51)
      at oracle.dbtools.crest.imports.erwin.ERwinHandler$Runner.run(ERwinHandler.java:126)
      at java.lang.Thread.run(Thread.java:745)
    2015-02-11 14:38:12,680 [main] INFO  ApplicationView - Oracle SQL Developer Data Modeler 4.1.0.866
    2015-02-11 16:13:44,218 [Thread-33] ERROR ERwinHandler - ERwinHandler - Unable to parse ERwin 7.x file: <file_Path>
    java.lang.OutOfMemoryError: Java heap space

  • Want parse huge xml file for CDATA

    HI all
    I want to parse hude xml file for getting values of CDATA
    can u plz give me sample code for that
    here i am attaching the part of my xml file
    <initParams>
    <param description="simulation mode " name="smtpSimulationMode" passOn="false" required="false" type="bool" varSubstitute="false">
    <![CDATA[false]]>
    </param>
    <param description="full name of smtp host" name="smtpHost" passOn="false" required="true" type="string" varSubstitute="false">
    <![CDATA[222222]]>
    </param>
    <param description="smtpUserName for authentication" name="smtpUserName" passOn="false" required="false" type="string" varSubstitute="false"/>
    <param description="smtpUserPassword for authentication" name="smtpUserPassword" passOn="false" required="false" type="string" varSubstitute="false"/>
    <param description="ip address for remote server" name="serverId" passOn="false" required="true" type="string" varSubstitute="false">
    <![CDATA[1111111]]>
    </param>
    <param description="location of file on remote server side" name="fileRemoteLocation" passOn="false" required="false" type="string" varSubstitute="false">
    <![CDATA[test/]]>
    </param>
    <param description="user name for authentication" name="userName" passOn="false" required="true" type="string" varSubstitute="false">
    <![CDATA[abc]]>
    </param>
    </initParams>
    thanks in advance

    There are several Java XML API's available. SAX, JXpath, DOM4J, Xerces, etcetera.

  • Couldn't parse image from XML file using NSXMLParser

    Hi all, Since i am newbie to developing iPhone application, i have problem in parsing XML data.
    I use the following code for parsing XML file, this is RootViewController.h file
    #import <UIKit/UIKit.h>
    #import "SlideMenuView.h"
    #define kNameValueTag 1
    #define kColorValueTag 2
    #define kSwitchTag 100
    @class DetailViewController;
    @interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
    DetailViewController *detailViewController;
    UITableView *myTable;
    UIActivityIndicatorView *activityIndicator;
    UIButton *btn;
    CGSize cellSize;
    NSXMLParser *rssParser;
    NSMutableArray *stories;
    NSMutableDictionary *item;
    NSString *currentElement;
    NSMutableString *currentTitle, *currentDate, *currentSummary, *currentLink, *currentImage;
    SlideMenuView *slideMenu;
    NSMutableArray *buttonArray;
    UIButton *rubic;
    UIButton *buurt;
    UIButton *beeld;
    UILabel *lbl;
    NSString *url;
    @property (nonatomic, retain) UITableView *myTable;
    @property (nonatomic, retain) DetailViewController *detailViewController;
    @property (nonatomic, retain) SlideMenuView *slideMenu;
    @property (nonatomic, retain) UIButton *btn;
    @property (nonatomic, retain) NSMutableArray *buttonArray;
    @property (nonatomic, retain) UIButton *rubic;
    @property (nonatomic, retain) UIButton *buurt;
    @property (nonatomic, retain) UIButton *beeld;
    @property (nonatomic, retain) UILabel *lbl;
    @end
    below is the RootViewController.m file,
    #import <Foundation/Foundation.h>
    #import "RootViewController.h"
    #import "DetailViewController.h"
    #import "SlideMenuView.h"
    @implementation RootViewController
    @synthesize rubic, buurt, beeld, detailViewController, myTable, btn, buttonArray, slideMenu, lbl;
    - (void)parseXMLFileAtURL:(NSString *)URL {
    stories = [[NSMutableArray alloc] init];
    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];
    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];
    [rssParser parse];
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"item"]) {
    // clear out our story item caches...
    item = [[NSMutableDictionary alloc] init];
    currentTitle = [[NSMutableString alloc] init];
    currentDate = [[NSMutableString alloc] init];
    currentSummary = [[NSMutableString alloc] init];
    currentLink = [[NSMutableString alloc] init];
    currentImage = [[NSMutableString alloc] init];
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"item"]) {
    // save values to an item, then store that item into the array...
    [item setObject:currentTitle forKey:@"title"];
    [item setObject:currentSummary forKey:@"summary"];
    [item setObject:currentDate forKey:@"date"];
    [item setObject:currentImage forKey:@"enclosure"];
    [stories addObject:[item copy]];
    NSLog(@"adding story: %@", currentTitle);
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"title"]) {
    [currentTitle appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {
    [currentSummary appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {
    [currentDate appendString:string];
    } else if ([currentElement isEqualToString:@"enclosure"]) {
    [currentImage appendString:string];
    - (void)parserDidEndDocument:(NSXMLParser *)parser {
    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];
    NSLog(@"all done!");
    NSLog(@"stories array has %d items", [stories count]);
    [myTable reloadData];
    - (void)loadView {
    //self.title = @"GVA_iPhone";
    //UIImage *img = [UIImage imageNamed: @"gva_v2.1.png"];
    CGRect frame = [[UIScreen mainScreen] bounds];
    UIView *aView = [[UIView alloc] initWithFrame:frame];
    aView.backgroundColor = [UIColor grayColor];
    self.view = aView;
    [aView release];
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 33.0, 320.0, 30.0)];
    lbl.backgroundColor = [UIColor colorWithRed:21.0/255.0 green:113.0/255.0 blue:194.0/255.0 alpha:1.0];
    lbl.textColor = [UIColor whiteColor];
    lbl.font = [UIFont boldSystemFontOfSize:18.0];
    [self.view addSubview:lbl];
    [lbl release];
    buttonArray = [[NSMutableArray alloc] init];
    for(int i = 1; i < 4; i++)
    // Rounded rect is nice
    //UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // Give the buttons a width of 100 and a height of 30. The slide menu will take care of positioning the buttons.
    // If you don't know that 100 will be enough, use my function to calculate the length of a string. You find it on my blog.
    [btn setFrame:CGRectMake(0.0f,3.0f, 120.0f, 30.0f)];
    switch(i){
    case 1:
    [btn setTitle:[NSString stringWithFormat:@" Snel", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    lbl.text = @" Snel";
    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    case 2:
    [btn setTitle:[NSString stringWithFormat:@" Binnenland", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    case 3:
    [btn setTitle:[NSString stringWithFormat:@" Buitenland", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    [btn release];
    slideMenu = [[SlideMenuView alloc]initWithFrameColorAndButtons:CGRectMake(0.0, 3.0, 330.0, 30.0) backgroundColor:[UIColor blackColor] buttons:buttonArray];
    [self.view addSubview:slideMenu];
    UITableView *aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 63.0, 320.0, 310.0)];
    aTableView.dataSource = self;
    aTableView.delegate = self;
    aTableView.rowHeight = 120;
    self.myTable = aTableView;
    [aTableView release];
    [self.view addSubview:myTable];
    rubic = [[UIButton alloc]initWithFrame:CGRectMake(0.0, 370.0, 105.0, 50.0)];
    [rubic setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [rubic addTarget:self action:@selector(buttonBinn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rubic];
    UILabel *lblRub = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 385.0, 45.0, 12.0)];
    lblRub.text = @"Rubriek";
    lblRub.font = [UIFont boldSystemFontOfSize:11.0];
    lblRub.backgroundColor = [UIColor clearColor];
    lblRub.textColor = [UIColor whiteColor];
    [self.view addSubview:lblRub];
    UIImageView *imgCat = [[UIImageView alloc] initWithFrame:CGRectMake(58.0, 375.0, 39.0, 36.0)];
    imgCat.image = [UIImage imageNamed:@"category_icon.png"];
    [self.view addSubview:imgCat];
    buurt = [[UIButton alloc] initWithFrame:CGRectMake(105.0, 370.0, 108.0, 50.0)];
    [buurt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [buurt addTarget:self action:@selector(buttonBuurt:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buurt];
    UILabel *lblGlo = [[UILabel alloc]initWithFrame:CGRectMake(112.0, 385.0, 59.0, 12.0)];
    lblGlo.text = @"In de Buurt";
    lblGlo.font = [UIFont boldSystemFontOfSize:11.0];
    lblGlo.backgroundColor = [UIColor clearColor];
    lblGlo.textColor = [UIColor whiteColor];
    [self.view addSubview:lblGlo];
    UIImageView *imgGlo = [[UIImageView alloc] initWithFrame:CGRectMake(173.0, 375.0, 39.0, 36.0)];
    imgGlo.image = [UIImage imageNamed:@"globe_icon.png"];
    [self.view addSubview:imgGlo];
    beeld = [[UIButton alloc]initWithFrame:CGRectMake(213.0, 370.0, 108.0, 50.0)];
    [beeld setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [beeld addTarget:self action:@selector(buttonBeeld:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:beeld];
    UILabel *lblCam = [[UILabel alloc]initWithFrame:CGRectMake(228.0, 385.0, 45.0, 12.0)];
    lblCam.text = @"In Beeld";
    lblCam.font = [UIFont boldSystemFontOfSize:11.0];
    lblCam.backgroundColor = [UIColor clearColor];
    lblCam.textColor = [UIColor whiteColor];
    [self.view addSubview:lblCam];
    UIImageView *imgCam = [[UIImageView alloc] initWithFrame:CGRectMake(276.0, 375.0, 39.0, 36.0)];
    imgCam.image = [UIImage imageNamed:@"camera_icon.png"];
    [self.view addSubview:imgCam];
    if([stories count] == 0) {
    [self parseXMLFileAtURL:@"http://iphone.concentra.exuvis.com/feed/rss/article/2/binnenland.xml"];
    cellSize = CGSizeMake([myTable bounds].size.width,60);
    - (IBAction)buttonPressed:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    - (IBAction)buttonClicked:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    - (IBAction)buttonTouched:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    -(void)buttonBinn:(id)sender
    [rubic setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    -(void)buttonBuurt:(id)sender
    [buurt setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    -(void)buttonBeeld:(id)sender
    [beeld setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
    - (void)dealloc {
    [myTable release];
    [detailViewController release];
    [super dealloc];
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [stories count];
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GVAiPhone"];
    if (cell == nil) {
    //CGRect cellFrame = CGRectMake(0, 0, 300, 65);
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"GVAiPhone"] autorelease];
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_icon.png"]];
    CGRect nameValueRect = CGRectMake(5, 5, 275, 35);
    UILabel *nameValue = [[UILabel alloc] initWithFrame:nameValueRect];
    nameValue.tag = kNameValueTag;
    nameValue.font = [UIFont fontWithName:@"Arial" size:15.0];
    nameValue.lineBreakMode = UILineBreakModeWordWrap;
    nameValue.numberOfLines = 2;
    [cell.contentView addSubview:nameValue];
    [nameValue release];
    CGRect colorValueRect = CGRectMake(5, 38, 275, 65);
    UILabel *colorValue = [[UILabel alloc] initWithFrame:colorValueRect];
    colorValue.tag = kColorValueTag;
    colorValue.font = [UIFont fontWithName:@"Arial" size:11.0];
    colorValue.textColor = [UIColor colorWithRed:130.0/255.0 green:135.0/255.0 blue:139.0/255.0 alpha:1.0];
    colorValue.lineBreakMode = UILineBreakModeWordWrap;
    colorValue.textAlignment = UITextAlignmentLeft;
    colorValue.numberOfLines = 6;
    [cell.contentView addSubview:colorValue];
    [colorValue release];
    // Set up the cell
    //cell.text = [theSimpsons objectAtIndex:indexPath.row];
    //cell.hidesAccessoryWhenEditing = YES;
    NSUInteger storyIndex = [indexPath row];
    NSDictionary *rowData = [stories objectAtIndex:storyIndex];
    UILabel *name = (UILabel *)[cell.contentView viewWithTag:kNameValueTag];
    name.text = [rowData objectForKey:@"title"];
    //name.lineBreakMode;
    //UIImage *image =[UIImage imageNamed: currentImage];imageWithContentsOfFile
    //image.size.width = 50;
    //iimage.size.height = 50;
    //cell.image = [UIImage imageNamed:currentImage];
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_icon.png"]];
    UILabel *color = (UILabel *)[cell.contentView viewWithTag:kColorValueTag];
    color.text = [rowData objectForKey:@"summary"];
    return cell;
    @end
    - here the actual problem is the xml node <enclosure> contains images but in using the method "didEndElement" , it doesn't parse into the <enclosure> node. ya so please help me in parsing and getting the image.
    Waiting for your help !!
    -Sathiya

    Hi, how did you solve your problem in detail. I'm having the same problem with this rss-feed: www.spiegel.de/index.rss
    I cannot parse the url of the images. I'm looking forward to your answer.

  • URGENT --  Perofrmance issue while creating Huge XML file

    All XML Experts Please Help....Thanks a lot in Advance
    We are trying to create a XML file for a huge table.. 5 million rows and the performance is ver very bad.. Can some body help by giving me an idea what what my best approch could be... or what am I doing wrong in in the code below
    CREATE OR REPLACE PROCEDURE Sales_1_Generate_Xml IS
    temp_clob CLOB;
    temp_buffer VARCHAR2(1);
    amount BINARY_INTEGER := 1;
    position INTEGER := 1;
    filehandle utl_file.file_type;
    error_number NUMBER;
    error_message VARCHAR2(100);
    length_count INTEGER;
    qryctx dbms_xmlgen.ctxhandle;
    BEGIN
    qryctx := dbms_xmlgen.newcontext('select /* INDEX UF_SALES(UF_SALES_IX16) */
    TRANSACTION_NUMBER     "Transaction_Number",
    TRANSACTION_TYPE_ID     "Transaction_Type_ID",
    PROCESS_FISCAL_DATE_ID     "Process_Fiscal_Date_ID",
    INVOICE_FISCAL_DATE_ID     "Invoice_Fiscal_Date_ID",
    ORDER_FISCAL_DATE_ID     "Order_Fiscal_Date_ID",
    PROCESS_CALENDAR_DATE_ID     "Process_Calendar_Date_ID",
    INVOICE_CALENDAR_DATE_ID     "Invoice_Calendar_Date_ID",
    ORDER_CALENDAR_DATE_ID     "Order_Calendar_Date_ID",
    CURRENT_TM_ID     "Current_TM_ID",
    CUSTOMER_ID     "Customer_ID",
    CUSTOMER_TYPE_ID     "Customer_Type_ID",
    CUSTOMER_LEVEL_ID     "Customer_Level_ID",
    ACCOUNT_TYPE_ID     "Account_Type_ID",
    TRADE_CLASS_ID     "Trade_Class_ID",
    DISTRIBUTOR_ID     "Distributor_ID",
    PRODUCT_ID     "Product_ID",
    ORDERED_PRODUCT_ID     "Ordered_Product_ID",
    BRAND_TYPE_ID     "Brand_Type_ID",
    LABEL_TYPE_ID     "Label_Type_ID",
    BRAND_LABEL_ID     "Brand_Label_ID",
    PRICED_BY_ID     "Priced_By_ID",
    SALES_UOM_ID     "Sales_UOM_ID",
    PURCHASING_UOM_ID     "Purchasing_UOM_ID",
    PRICING_UOM_ID     "Pricing_UOM_ID",
    NET_COST     "Net_Cost",
    NPA_S     "NPA_S",
    CMA_S     "CMA_S",
    NOT_S     "NOT_S",
    TOTAL_NATIONAL_ALLOWANCE_S     "Total_National_Allowance_S",
    LPA_S     "LPA_S",
    LMA_S     "LMA_S",
    LOT_S     "LOT_S",
    TOTAL_LOCAL_ALLOWANCE_S     "Total_Local_Allowance_S",
    TOTAL_ALLOWANCES_S     "Total_Allowances_S",
    LPC     "LPC",
    LPC_EXTENDED     "LPC_Extended",
    LPF     "LPF",
    LPF_EXTENDED     "LPF_Extended",
    TRUE_COST     "True_Cost",
    CDE     "CDE",
    LPP     "LPP",
    SURCHARGE     "Surcharge",
    COMBINED_SURCHARGE     "Combined_Surcharge",
    TOTAL_SURCHARGES     "Total_Surcharges",
    MARKET_COST     "Market_Cost",
    INSIDE_PAD     "Inside_Pad",
    SALES_REP_COST     "Sales_Rep_Cost",
    SALES_REP_MARGIN     "Sales_Rep_Margin",
    SALES_PRICE     "Sales_Price",
    SALES_TRUE_MARGIN     "Sales_True_Margin",
    NVD     "NVD",
    LVD     "LVD",
    NID     "NID",
    LID     "LID",
    TOTAL_VD     "Total_VD",
    TOTAL_ID     "Total_ID",
    TOTAL_DEVIATIONS     "Total_Deviations",
    GP1     "GP1",
    GP2     "GP2",
    DEVIATED_COST     "Deviated_Cost",
    ACTUAL_COST     "Actual_Cost",
    SALES_TAX     "Sales_Tax",
    QUANTITY_ORDERED     "Quantity_Ordered",
    QUANTITY_SHIPPED     "Quantity_Shipped",
    QUANTITY_DEVIATED     "Quantity_Deviated",
    QUANTITY_SUBBED     "Quantity_Subbed",
    UNITS_ORDERED     "Units_Ordered",
    EACHES_ORDERED     "Eaches_Ordered",
    EACH_CONVERSION_FACTOR     "Each_Conversion_Factor",
    UNITS_SHIPPED     "Units_Shipped",
    EACHES_SHIPPED     "Eaches_Shipped",
    SHIP_WEIGHT     "Ship_Weight",
    ACTUAL_GP_DLR     "Actual_GP_Dlr",
    TRUE_GP_DLR     "True_GP_Dlr",
    LANDED_GP_DLR     "Landed_GP_Dlr",
    LANDED_ACTUAL_GP_DLR     "Landed_Actual_GP_Dlr",
    INVOICE_GP_DLR     "Invoice_GP_Dlr",
    INVOICE_ACTUAL_GP_DLR     "Invoice_Actual_GP_Dlr",
    ADJUSTED_ACTUAL_GP_DLR     "Adjusted_Actual_GP_Dlr",
    EB_S     "EB_S",
    MB_S     "MB_S",
    ACTUAL_TM_ID     "Actual_TM_ID",
    ACTUAL_TM_NAME     "Actual_TM_Name",
    ACTUAL_DSM_ID     "Actual_DSM_ID",
    ACTUAL_DSM_NAME     "Actual_DSM_Name",
    INVOICE_NUMBER      "Invoice_Number ",
    CONTRACT_NUMBER     "Contract_Number",
    CUSTOMER_NUMBER     "Customer_Number",
    CUSTOMER     "Customer",
    PRODUCT_NUMBER     "Product_Number",
    MASTER_DISTRIBUTOR_ID     "Master_Distributor_ID",
    ORDERED_PRODUCT_NUMBER     "Ordered_Product_Number",
    NATIVE_PRODUCT_STATUS     "Native_Product_Status",
    NATIVE_PRICED_BY_INDICATOR     "Native_Priced_By_Indicator",
    EXTRACTION_TIME     "Extraction_Time"
    from uf_sales where distributor_id in (''5139'',
    ''5140'',
    ''5145'',
    ''5150'',
    ''5160'',
    ''5175'',
    ''5180'',
    ''5210'',
    ''5220'',
    ''5230'')
    DBMS_XMLGen.setRowTag(qryctx,'Sales_Record');
    DBMS_XMLGen.setRowSetTag(qryctx,'Sales_Set');
    temp_clob:=dbms_xmlgen.getxml(qryctx);
    length_count := dbms_lob.getlength(temp_clob);
    dbms_output.put_line('Internal LOB size is: ' || length_count);
    filehandle := utl_file.fopen('DATA_EXTRACT','Sales_1.xml','Wb',32767);
    WHILE length_count <> 0 LOOP
    dbms_lob.read (temp_clob, amount, position, temp_buffer);
    --utl_file.put (filehandle, temp_buffer);
    utl_file.put_raw(filehandle, utl_raw.cast_to_raw(temp_buffer));
    position := position + 1;
    length_count := length_count - 1;
    temp_buffer := null;
    END LOOP;
    dbms_output.put_line('Exit the loop');
    utl_file.fclose(filehandle);
    DBMS_XMLGen.closeContext(qryctx);
    dbms_output.put_line('Close the file');
    EXCEPTION
    WHEN OTHERS THEN
    BEGIN
    error_number := sqlcode;
    error_message := substr(sqlerrm ,1 ,100);
    dbms_output.put_line('Error #: ' || error_number);
    dbms_output.put_line('Error Message: ' || error_message);
    utl_file.fclose_all;
    END;
    END;
    /

    OK, so you are writing the file with UTL_FILE. How long is the whole process taking. Have you timed the time taken to generate the temp_clob with the result Vs the time to write the output to a file.

  • Parse of a xml file to an java object model

    Hello,
    I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
    I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
    Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
    public static void readFile(String root){
              DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   String contents = scanner.next();
                   scanner.close();
                   Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
                   Node node = null;
                   NodeList nodes = null;
                   Element element = document.getDocumentElement();
                   System.out.println(element.getNodeName());
                   NodeList subNodes;
                   NamedNodeMap attributes;
                   //if (element.hasAttributes())
                   visitNodes(element);
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         private static void visitNodes (Node node){
              for(Node childNode = node.getFirstChild(); childNode!=null;){
                   if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                        System.out.println("Document node Name " + childNode.getNodeName());
                        visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                        System.out.println("Node Name " + childNode.getNodeName());
                        if (childNode.hasAttributes()){
                             visitAttributes(childNode.getAttributes());
                        if (childNode.hasChildNodes()){
                             visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                        System.out.println("Node value " + childNode.getNodeValue());
                   Node nextChild = childNode.getNextSibling();
                   childNode = nextChild;
         private static void visitAttributes(NamedNodeMap attributes){
              Node node;
              for(int i = 0; i < attributes.getLength(); i++){
                   node = attributes.item(i);
                   System.out.print(node.getNodeName() + " ");
                   System.out.print(node.getNodeValue() + " ");
                  }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
    But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
    Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
    When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
    Have you any other suggestions? All the help or idea will be well received.
    Thanks for all.

    Hello again,
    My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
    I have solved my initial problem with the xml parser.
    Firstly, I read the complete XML file, validated previously.
    The code I've used is this:
    public static String readCompleteFile (String root){
              String content = "";
              try {
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   content = scanner.next();
                   scanner.close();
              } catch (IOException e) {
                   e.printStackTrace();
              return content;
         }Now, I've the file in memory and I hope I can explain me better.
    I can receive different types of XML that could be or not partly equals.
    For this purpose I've created an external jar library with all the possible objects contained in my xml files.
    Each one of this objects depend on other, until found leaf nodes.
    For example, If I receive one xml with a scheme like the next:
    <Person>
        <Name>Juliet</Name>
        <Father Age="30r">Peter</Father>
        <Mother age="29">Theresa</Mother>
        <Brother>
        </Brother>
        <Education>
            <School>
            </school>
        </education>
    </person>
    <person>
    </person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
    The method that I must implement as constructor in every object is similar to this:
    public class Person{
      final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
      private String name;
         private Father father;
         private Mother mother;
         private ArrayList brothers;
         private Education education;
         public Person(String xml){
           XmlUtil utilXml = new XmlUtil();          
              String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
              String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
              String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
              String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
              if (!xmlFather.equals("")){
                   this.setFather(new Father(xmlFather));
              if (!xmlMother.equals("")){
                   this.setMother(new Father(xmlMother));
              if (!xmlBrothers.equals("")){
                ArrayList aux = new ArrayList();
                String xmlBrother;
                while xmlBrothers != null && !xmlBrothers.equals("")){
                  xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
                  aux.add(new Brother(xmlBrother);
                  xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
                this.setBrothers(aux);
              if (!xmlEducation.equals("")){
                   this.setEducation(new Father(xmlEducation));     
    }If the object is a leaf object, the constructor will be like this:
    public class Mother {
         //Elements
         private String name;
         private String age;
         public Mother(String xml){          
              XmlUtil utilXml = new XmlUtil();
              HashMap objects = utilXml.parsearString(xml);
              ArraysList objectsList = new ArrayList();
              String[] Object = new String[2];
              this.setName((String)objects.get("Mother"));
              if (objects.get("attributes")!= null){
                   objectsList = objects.get("attributes");
                   for (int i = 0; i < objectsList.size();i++){
                     Object = objectsList.get(i);
                     if (object[0].equals("age"))
                       this.setAge(object[1]);
                     else
         }Each class will have its getter and setter but I do not have implemented in the examples.
    Finally, the parser is as follows:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    public class XmlUtil {
         public HashMap parsearString(String contenido){
              HashMap objet = new HashMap();
              DocumentBuilderFactory factory;
              DocumentBuilder builder;
              Document document;
              try{
                   if (content != null && !content.equals("")){
                        factory = DocumentBuilderFactory.newInstance();
                        builder = factory.newDocumentBuilder();
                        document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                        object = visitNodes(document);                    
                   }else{
                        object = null;
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
                   return null;
              } catch (SAXException e) {
                   e.printStackTrace();
                   return null;
              } catch (IOException e) {
                   e.printStackTrace();
                   return null;
              return object;
         private HashMap visitNodes (Node node){
              String nodeName = "";
              String nodeValue = "";
              ArrayList attributes = new ArrayList();
              HashMap object = new HashMap();
              Node childNode = node.getFirstChild();
              if (childNode.getNodeType() == Node.ELEMENT_NODE){
                   nodeName = childNode.getNodeName();                    
                   if (childNode.hasAttributes()){
                        attributes = visitAttributes(childNode.getAttributes());
                   }else{
                        attributes = null;
                   nodeValue = getNodeValue(childNode);
                   object.put(nodeName, nodeValue);
                   object.put("attributes", attributes);
              return object;
         private static String getNodeValue (Node node){          
              if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
                   return node.getFirstChild().getNodeValue();
              else
                   return "";
         private ArrayList visitAttributes(NamedNodeMap attributes){
              Node node;
              ArrayList ListAttributes = new ArrayList();
              String [] attribute = new String[2];
              for(int i = 0; i < attributes.getLength(); i++){
                   atribute = new String[2];
                   node = attributes.item(i);
                   if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                        attribute[0] = node.getNodeName();
                        attribute[1] = node.getNodeValue();
                        ListAttributes.add(attribute);
              return ListAttributes;
    }This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
    The code I use is:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class UtilClasses {
         public Object UtilClasses(String package, String object, String xml){
              try {
                Class class = Class.forName(package + "." + object);
                //parameter types for methods
                Class[] partypes = new Class[]{Object.class};
                //Create method object . methodname and parameter types
                Method meth = class.getMethod(object, partypes);
                //parameter types for constructor
                Class[] constrpartypes = new Class[]{String.class};
                //Create constructor object . parameter types
                Constructor constr = claseObjeto.getConstructor(constrpartypes);
                //create instance
                Object obj = constr.newInstance(new String[]{xml});
                //Arguments to be passed into method
                Object[] arglist = new Object[]{xml};
                //invoke method!!
                String output = (String) meth.invoke(dummyto, arglist);
                System.out.println(output);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
              return null;
         }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
    I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
    greetings.

Maybe you are looking for