类来解析xml元素
下了个通过类来解析xml元素的程序,但是有错,提示
org.xml.sax.SAXException: System property org.xml.sax.driver not specified
at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:90)
请各位高手指教
Custormer.java
public class Customer {
// Customer member variables.
public String firstName = "";
public String lastName = "";
public String custId = "";
public void print( PrintStream out ) {
out.println( "Customer: " );
out.println( " First Name -> " + firstName );
out.println( " Last Name -> " + lastName );
out.println( " Customer Id -> " + custId );
}
}
Test.java
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class Test
extends DefaultHandler {
private Customer cust = new Customer();
private CharArrayWriter contents = new CharArrayWriter();
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes attr) throws SAXException {
contents.reset();
}
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
if (localName.equals("FirstName")) {
cust.firstName = contents.toString();
}
if (localName.equals("LastName")) {
cust.lastName = contents.toString();
}
if (localName.equals("CustId")) {
cust.custId = contents.toString();
}
}
public void characters(char[] ch, int start, int length) throws
SAXException {
contents.write(ch, start, length);
}
public Customer getCustomer() {
return cust;
}
public static void main(String[] argv) {
System.out.println("xmlhomework3:");
try {
parser.parse(new InputSource(new FileReader("test.xml")), new Test());
Test t = new Test();
xr.setContentHandler( t );
Customer cust = t.getCustomer();
cust.print(System.out);
}
catch (Exception e) {
e.printStackTrace();
}
}
}