SAXParseException为getSystemId()返回null

时间:2011-04-18 20:08:33

标签: java saxparseexception

为什么SAXParseException为getSystemId()返回null?什么是系统标识符?

    import java.io.StringReader;

    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;

    import org.xml.sax.ErrorHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.XMLReader;

    public class MainClass {
      static public void main(String[] arg) throws Exception{
        boolean validate = false;

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setValidating(validate);

        XMLReader reader = null;
          SAXParser parser = spf.newSAXParser();
          reader = parser.getXMLReader();

        reader.setErrorHandler(new MyErrorHandler());
          reader.parse(new InputSource(new StringReader(xmlString)));
    }
      static String xmlString = "<PHONEBOOK>" +
      "  <PERSON>" +
      "   <NAME>Joe Wang</NAME>" +
      "   <EMAIL>joe@yourserver.com</EMAIL>" +
      "   <TELEPHONE>202-999-9999</TELEPHONE>" +
      "   <WEB>www.java2s.com</WEB>" +
      "  </PERSON>" +
      "  <PERSON>   " +
      "<NAME>Karol</NAE>" +    // error here
      "   <EMAIL>karol@yourserver.com</EMAIL>" +
      "   <TELEPHONE>306-999-9999</TELEPHONE>" +
      "   <WEB>www.java2s.com</WEB>" +
      "  </PERSON>" +
      "  <PERSON>" +
      "   <NAME>Green</NAME>" +
      "   <EMAIL>green@yourserver.com</EMAIL>" +
      "   <TELEPHONE>202-414-9999</TELEPHONE>" +
      "   <WEB>www.java2s.com</WEB>" +
      "  </PERSON>" +
      "  </PHONEBOOK>";
    }
    class MyErrorHandler implements ErrorHandler {
      public void warning(SAXParseException e) throws SAXException {
        show("Warning", e);
        throw (e);
      }

      public void error(SAXParseException e) throws SAXException {
        show("Error", e);
        throw (e);
      }

      public void fatalError(SAXParseException e) throws SAXException {
        show("Fatal Error", e);
        throw (e);
      }

      private void show(String type, SAXParseException e) {
        System.out.println(type + ": " + e.getMessage());
        System.out.println("Line " + e.getLineNumber() + " Column "
            + e.getColumnNumber());
        System.out.println("System ID: " + e.getSystemId());
        System.out.println(e);

      }
    }

2 个答案:

答案 0 :(得分:4)

XML中的“系统标识符”是您从中获得的物理位置。当您只解析内存中的字符串时,它根本没有系统标识符,除非您进行额外的调用以给它一个。

在这种情况下,您可以拨打InputSource.setSystemId

答案 1 :(得分:1)

系统标识符是您可以指定的URI,因此它可以由EntityResolver用于决定在xml解析期间如何解析相对路径。无论是物理位置还是标签都取决于您。当然,在您的示例中,您没有任何要解决的问题,因此不需要它。