XML - Managing Data Exchange/Parsing XML files/Answers
Appearance
This java class file is associated with the movies.xml file used in the chapter. Place this java file and movies.xml in the same directory. After compiling, this needs to be run from a command window and the format is: > java SPParser movies.xml
importjavax.xml.parsers.*;importorg.xml.sax.*;importorg.w3c.dom.*;importjava.io.*;publicclassSPParser{staticDocumentdoc;publicSPParser(Stringfilename){//filename S/B the name of the XML file to parseFilefile=newFile(filename);try{DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();DocumentBuilderparser=factory.newDocumentBuilder();doc=parser.parse(file);System.out.println(file+" is well-formed.");}catch(SAXExceptione){System.out.println(e.getMessage());}catch(IOExceptione){System.out.println(e.getMessage());}catch(ParserConfigurationExceptione){System.out.println("Could not locate a JAXP parser");}}publicvoidreadData(Noden){System.out.println("Printing data and attributes");NamedNodeMapattributes=n.getAttributes();StringstrAttributes="Production Company- '"+attributes.item(0).getNodeValue();if(attributes.getLength()==2)//There are two attributes in the movies.xml filestrAttributes+="' , Loaned To - '"+attributes.item(1).getNodeValue()+"' ,";elsestrAttributes+="' , Not out , ";NodeListvalues=n.getChildNodes();StringdataString="Movies Data: "+strAttributes;intancestor=0;for(inti=0;i<values.getLength();i++){Nodechild=values.item(i);if(child.getNodeType()!=Node.TEXT_NODE){Stringinsert=child.getFirstChild().getNodeValue();if(insert.trim().length()!=0&&ancestor==0){dataString+="Movie Title - '"+insert+"', ";ancestor=1;}elseif(insert.trim().length()!=0&&ancestor==1){dataString+="Director - '"+insert+"'.";ancestor=0;}}}//End of for-loopSystem.out.println(dataString);System.out.println();}//End of insertStatements()publicstaticvoidmain(String[]args){SPParserp=newSPParser("movies.xml");NodeListn=doc.getElementsByTagName("movie");for(inti=0;i<n.getLength();i++){p.readData(n.item(i));}}//End of main()}//End of SPParser class |