Sunday, 19 October 2014

creating objects from xml parsing



I am a new programmer and I am having trouble with a project I am working on. I am trying to parse a xml file using a Saxparser instead of getting user input. My xml file has multiple types of "citations" such as books, journal articles ext. I am having trouble filling an object hierarchy by parsing an xml, I have the appropriate classes with their respective constructers and getter and setter methods to create the objects. My only question is how to create these objects while parsing by overriding these methods below in my main class.



public class main extends DefaultHandler{

@Override
public void startElement(String s, String s1, String tagname, Attributes attr ) throws SAXException{
if(tagname.equals("Book")){
}

}

@Override
public void characters(char [] ac, int i, int s)throws SAXException{

}

@Override
public void endElement(String s, String s1, String tag)throws SAXException{

}


public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
// Create scanner
Scanner OswegoNote = new Scanner(System.in);
//Create a parser factory
SAXParserFactory factory = SAXParserFactory.newInstance();
//make the parser
SAXParser saxParser = factory.newSAXParser();
XMLReader parser = saxParser.getXMLReader();
//create a handler
main handler = new main();
//tell the parser to use the handler
parser.setContentHandler(handler);
//Read and parse the document
parser.parse("xmlFile.xml");


Below is part of the xml file I am attempting to parse and retrieve the shown values for each citation type.



<Citation>
<Book>
<Name>A Wavelet Tour of Signal Processing</Name>
<Publisher>Academic Press</Publisher>
<PublicationDate>01/01/2009</PublicationDate>
<PublicationPlace>Burlington,MA</PublicationPlace>
<Authors>
<author>Stephanie M Mallot</author>
</Authors>
<Keywords>
<Keyword>DSP</Keyword>
<Keyword>Wavelets</Keyword>
<Keyword>Sparse Data</Keyword>
</Keywords>
</Book>
</Citation>


<Citation>
<JournalArticle>
<Name>The attractions of stupidity</Name>
<TitleOfJournal>The St. Croix Review</TitleOfJournal>
<PublicationDate>October, 2002</PublicationDate>
<volNumber>30</volNumber>
<IssueNumber>2</IssueNumber>
<Authors>
<author>Harry Hank Hirsh</author>
<author>Mark Harold Coen</author>
<author>Michael Charles Mozer</author>
</Authors>
<Pages StartPage="6" EndPage="10"/>
<Keywords>
<Keyword>Psychology</Keyword>
<Keyword>Sociology</Keyword>
<Keyword>Intelligence</Keyword>
<Keyword>Sexuality</Keyword>
</Keywords>
</JournalArticle>
</Citation>

No comments:

Post a Comment