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
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import java.io.*;
public class SPParser
{
static Document doc;
public SPParser(String filename)
{
//filename S/B the name of the XML file to parse
File file = new File(filename);
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.parse(file);
System.out.println(file + " is well-formed.");
}
catch (SAXException e)
{
System.out.println( e.getMessage());
}
catch (IOException e)
{
System.out.println( e.getMessage());
}
catch (ParserConfigurationException e)
{
System.out.println("Could not locate a JAXP parser");
}
}
public void readData(Node n)
{
System.out.println("Printing data and attributes");
NamedNodeMap attributes = n.getAttributes();
String strAttributes = "Production Company- '" + attributes.item(0).getNodeValue();
if (attributes.getLength() == 2) //There are two attributes in the movies.xml file
strAttributes += "' , Loaned To - '" + attributes.item(1).getNodeValue() + "' ,";
else
strAttributes += "' , Not out , ";
NodeList values = n.getChildNodes();
String dataString = "Movies Data: " + strAttributes;
int ancestor = 0;
for (int i = 0; i < values.getLength(); i++)
{
Node child = values.item(i);
if (child.getNodeType() != Node.TEXT_NODE)
{
String insert = child.getFirstChild().getNodeValue();
if (insert.trim().length() != 0 && ancestor == 0)
{
dataString += "Movie Title - '"+insert+"', ";
ancestor = 1;
}
else if (insert.trim().length() != 0 && ancestor == 1)
{
dataString += "Director - '"+insert+"'.";
ancestor = 0;
}
}
}//End of for-loop
System.out.println(dataString);
System.out.println();
}//End of insertStatements()
public static void main(String[] args)
{
SPParser p = new SPParser("movies.xml");
NodeList n = doc.getElementsByTagName("movie");
for (int i = 0; i < n.getLength(); i++)
{
p.readData(n.item(i));
}
}//End of main()
}//End of SPParser class
|