Java by API/javax.xml.parsers/SAXParserFactory

Материал из Java эксперт
Перейти к: навигация, поиск

SAXParserFactory: isNamespaceAware()

/*
Parser will be namespace aware
Parser will validate XML
Parser object is: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@21b6d 
 */
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class MainClass {
  public static void main(String args[]) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ")
        + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    SAXParser parser = null;
    try {
      parser = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
      e.printStackTrace(System.err);
    } catch (SAXException e) {
      e.printStackTrace(System.err);
    }
    System.out.println("Parser object is: " + parser);
  }
}





SAXParserFactory: isValidating()

/*
Parser will be namespace aware
Parser will validate XML
Parser object is: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@21b6d 
 */
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class MainClass {
  public static void main(String args[]) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ")
        + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    SAXParser parser = null;
    try {
      parser = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
      e.printStackTrace(System.err);
    } catch (SAXException e) {
      e.printStackTrace(System.err);
    }
    System.out.println("Parser object is: " + parser);
  }
}





SAXParserFactory: newInstance()

import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MainClass {
  public static void main(String args[]) {
    try {
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser = factory.newSAXParser();
      DefaultHandler handler = new DefaultHandler() {
        boolean name = false;
        public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {
          if (qName.equalsIgnoreCase("NAME")) {
            name = true;
          }
        }
        public void characters(char ch[], int start, int length) throws SAXException {
          if (name) {
            System.out.println("Name: " + new String(ch, start, length));
            name = false;
          }
        }
      };
      saxParser.parse(new InputSource(new StringReader(xmlString)), handler);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  static String xmlString = "<PHONEBOOK>" +
      "  <PERSON>" +
      "   <NAME>Joe Wang</NAME>" +
      "   <EMAIL>joe@yourserver.ru</EMAIL>" +
      "   <TELEPHONE>202-999-9999</TELEPHONE>" +
      "   <WEB>www.jexp.ru</WEB>" +
      "  </PERSON>" +
      "  <PERSON>   " +
      "<NAME>Karol</NAME>" +
      "   <EMAIL>karol@yourserver.ru</EMAIL>" +
      "   <TELEPHONE>306-999-9999</TELEPHONE>" +
      "   <WEB>www.jexp.ru</WEB>" +
      "  </PERSON>" +
      "  <PERSON>" +
      "   <NAME>Green</NAME>" +
      "   <EMAIL>green@yourserver.ru</EMAIL>" +
      "   <TELEPHONE>202-414-9999</TELEPHONE>" +
      "   <WEB>www.jexp.ru</WEB>" +
      "  </PERSON>" +
      "  </PHONEBOOK>";
}





SAXParserFactory: setFeature(String name, boolean value)

/*
Parser object is: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@c9ba38
Start document: 
Start element: local name: PHONEBOOK qname: PHONEBOOK uri: 
Characters:   
Start element: local name: PERSON qname: PERSON uri: 
Characters:    
Start element: local name: NAME qname: NAME uri: 
Attributes:
  Name : firstName
  Type : CDATA
  Value: Joe
  Name : lastName
  Type : CDATA
  Value: Yin
Characters: Joe
Characters:  Yin
End element: local name: NAME qname: NAME uri: 
Characters:    
Start element: local name: EMAIL qname: EMAIL uri: 
Characters: joe@yourserver.ru
End element: local name: EMAIL qname: EMAIL uri: 
Characters:    
Start element: local name: TELEPHONE qname: TELEPHONE uri: 
Characters: 202-999-9999
End element: local name: TELEPHONE qname: TELEPHONE uri: 
Characters:    
Start element: local name: WEB qname: WEB uri: 
Characters: www.jexp.ru
End element: local name: WEB qname: WEB uri: 
Characters:   
End element: local name: PERSON qname: PERSON uri: 
Characters:   
End element: local name: PHONEBOOK qname: PHONEBOOK uri: 
End document: 
 */
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class MainClass {
  public static void main(String args[])throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    try {
     spf.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
     parser = spf.newSAXParser();
     System.out.println("Parser object is: "+ parser);
    }
    catch(Exception e) {
      e.printStackTrace(System.err);
    } 
    MySAXHandler handler = new MySAXHandler(); 
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
  }
  static String xmlString = "<?xml version=\"1.0\"?>" +
      "<addresses:address  xmlns:addresses=\"http://www.jexp.ru/AddressNamespace\">" +
      "<addresses:buildingnumber> 2934 </addresses:buildingnumber>" +
      "<addresses:street> South Street</addresses:street>" +
      "<addresses:city>Vancouver</addresses:city>" +
      "<addresses:state>BC</addresses:state>" +
      "<addresses:zip>V5V 4X6</addresses:zip>" +
      "</addresses:address>";
  
}
class MySAXHandler extends DefaultHandler {
  public void startDocument() {
    System.out.println("Start document: ");
  }    
    public void endDocument()  {
    System.out.println("End document: ");
  }
  
  public void startElement(String uri, String localName, String qname, 
                                                               Attributes attr)
  {
    System.out.println("Start element: local name: " + localName + " qname: " 
                                                        + qname + " uri: "+uri);
    int attrCount = attr.getLength();
    if(attrCount>0) {
      System.out.println("Attributes:"); 
      for(int i = 0 ; i<attrCount ; i++) {
        System.out.println("  Name : " + attr.getQName(i)); 
        System.out.println("  Type : " + attr.getType(i)); 
        System.out.println("  Value: " + attr.getValue(i)); 
      }
    } 
  }
  
  public void endElement(String uri, String localName, String qname) {
    System.out.println("End element: local name: " + localName + " qname: "
                                                         + qname + " uri: "+uri);
  }
  
  public void characters(char[] ch, int start, int length) {
    System.out.println("Characters: " + new String(ch, start, length));
  }
  public void ignorableWhitespace(char[] ch, int start, int length) {
    System.out.println("Ignorable whitespace: " + new String(ch, start, length));
  }
  public void startPrefixMapping(String prefix, String uri) {
    System.out.println("Start \"" + prefix + "\" namespace scope. URI: " + uri); 
  }
  public void endPrefixMapping(String prefix) {
    System.out.println("End \"" + prefix + "\" namespace scope."); 
  }
  public void warning(SAXParseException spe) {
    System.out.println("Warning at line "+spe.getLineNumber());
    System.out.println(spe.getMessage());
  }
  public void fatalError(SAXParseException spe) throws SAXException {
    System.out.println("Fatal error at line "+spe.getLineNumber());
    System.out.println(spe.getMessage());
    throw spe;
  }
}





SAXParserFactory: setNamespaceAware(boolean awareness)

/*
Parser will be namespace aware
Parser will validate XML
Parser object is: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@21b6d 
 */
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class MainClass {
  public static void main(String args[]) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ")
        + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    SAXParser parser = null;
    try {
      parser = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
      e.printStackTrace(System.err);
    } catch (SAXException e) {
      e.printStackTrace(System.err);
    }
    System.out.println("Parser object is: " + parser);
  }
}





SAXParserFactory: setValidating(boolean validating)

/*
Parser will be namespace aware
Parser will validate XML
Parser object is: com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@21b6d 
 */
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class MainClass {
  public static void main(String args[]) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ")
        + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    SAXParser parser = null;
    try {
      parser = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
      e.printStackTrace(System.err);
    } catch (SAXException e) {
      e.printStackTrace(System.err);
    }
    System.out.println("Parser object is: " + parser);
  }
}