Java by API/javax.xml/XMLConstants

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

XMLConstants.W3C_XML_SCHEMA_NS_URI

 
/*
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);
    try {
     SchemaFactory sf =
                     SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
     spf.setSchema(sf.newSchema(new SAXSource(new InputSource(new StringReader(schemaString)))));
     parser = spf.newSAXParser();
    }
    catch(SAXException e) {
      e.printStackTrace(System.err);
      System.exit(1);    
    } 
    catch(ParserConfigurationException e) {
      e.printStackTrace(System.err);
      System.exit(1);    
    }
    MySAXHandler handler = new MySAXHandler(); 
    System.out.println(schemaString);
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
  }
  static String xmlString = "<?xml version=\"1.0\"?>" +
      "<note>" +
      "<to>rtoName</to>" +
      "<from>FromName</from>" +
      "<heading>Info</heading>" +
      "<body>Message Body</body>" +
      "</note>";
  
  static String schemaString ="<?xml version=\"1.0\"?>" +
      "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
      " targetNamespace=\"http://www.jexp.ru\"" +
      " xmlns=\"http://www.jexp.ru\"" +
      " elementFormDefault=\"qualified\">" +
      "<xs:element name=\"note\">" +
      "<xs:complexType>" +
      "<xs:sequence>" +
      "<xs:element name=\"to\" type=\"xs:string\"/>" +
      "<xs:element name=\"from\" type=\"xs:string\"/>" +
      "<xs:element name=\"heading\" type=\"xs:string\"/>" +
      "<xs:element name=\"body\" type=\"xs:string\"/>" +
      "</xs:sequence>" +
                      "</xs:complexType>" +
                      "</xs:element>" +
                      "</xs:schema>";
}
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;
  }
}





XMLConstants.XMLNS_ATTRIBUTE

  
import java.io.FileReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class MainClass {
  public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.addNamespace("s", "uri:test:schedule");
    xPath.setNamespaceContext(nsContext);
    String result = xPath.evaluate("/s:schedule/@name", new InputSource(
        new FileReader("t.xml")));
    System.out.println(result);
  }
}
class SimpleNamespaceContext implements NamespaceContext {
  private Map<String, String> urisByPrefix = new HashMap<String, String>();
  private Map<String, Set> prefixesByURI = new HashMap<String, Set>();
  public SimpleNamespaceContext() {
    addNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    addNamespace(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
  }
  public synchronized void addNamespace(String prefix, String namespaceURI) {
    urisByPrefix.put(prefix, namespaceURI);
    if (prefixesByURI.containsKey(namespaceURI)) {
      (prefixesByURI.get(namespaceURI)).add(prefix);
    } else {
      Set<String> set = new HashSet<String>();
      set.add(prefix);
      prefixesByURI.put(namespaceURI, set);
    }
  }
  public String getNamespaceURI(String prefix) {
    if (prefix == null)
      throw new IllegalArgumentException("prefix cannot be null");
    if (urisByPrefix.containsKey(prefix))
      return (String) urisByPrefix.get(prefix);
    else
      return XMLConstants.NULL_NS_URI;
  }
  public String getPrefix(String namespaceURI) {
    return (String) getPrefixes(namespaceURI).next();
  }
  public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null)
      throw new IllegalArgumentException("namespaceURI cannot be null");
    if (prefixesByURI.containsKey(namespaceURI)) {
      return ((Set) prefixesByURI.get(namespaceURI)).iterator();
    } else {
      return Collections.EMPTY_SET.iterator();
    }
  }
}





XMLConstants.XML_NS_PREFIX

  
import java.io.FileReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class MainClass {
  public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.addNamespace("s", "uri:test:schedule");
    xPath.setNamespaceContext(nsContext);
    String result = xPath.evaluate("/s:schedule/@name", new InputSource(
        new FileReader("t.xml")));
    System.out.println(result);
  }
}
class SimpleNamespaceContext implements NamespaceContext {
  private Map<String, String> urisByPrefix = new HashMap<String, String>();
  private Map<String, Set> prefixesByURI = new HashMap<String, Set>();
  public SimpleNamespaceContext() {
    addNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    addNamespace(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
  }
  public synchronized void addNamespace(String prefix, String namespaceURI) {
    urisByPrefix.put(prefix, namespaceURI);
    if (prefixesByURI.containsKey(namespaceURI)) {
      (prefixesByURI.get(namespaceURI)).add(prefix);
    } else {
      Set<String> set = new HashSet<String>();
      set.add(prefix);
      prefixesByURI.put(namespaceURI, set);
    }
  }
  public String getNamespaceURI(String prefix) {
    if (prefix == null)
      throw new IllegalArgumentException("prefix cannot be null");
    if (urisByPrefix.containsKey(prefix))
      return (String) urisByPrefix.get(prefix);
    else
      return XMLConstants.NULL_NS_URI;
  }
  public String getPrefix(String namespaceURI) {
    return (String) getPrefixes(namespaceURI).next();
  }
  public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null)
      throw new IllegalArgumentException("namespaceURI cannot be null");
    if (prefixesByURI.containsKey(namespaceURI)) {
      return ((Set) prefixesByURI.get(namespaceURI)).iterator();
    } else {
      return Collections.EMPTY_SET.iterator();
    }
  }
}





XMLConstants.XML_NS_URI

  
import java.io.FileReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class MainClass {
  public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.addNamespace("s", "uri:test:schedule");
    xPath.setNamespaceContext(nsContext);
    String result = xPath.evaluate("/s:schedule/@name", new InputSource(
        new FileReader("t.xml")));
    System.out.println(result);
  }
}
class SimpleNamespaceContext implements NamespaceContext {
  private Map<String, String> urisByPrefix = new HashMap<String, String>();
  private Map<String, Set> prefixesByURI = new HashMap<String, Set>();
  public SimpleNamespaceContext() {
    addNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    addNamespace(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
  }
  public synchronized void addNamespace(String prefix, String namespaceURI) {
    urisByPrefix.put(prefix, namespaceURI);
    if (prefixesByURI.containsKey(namespaceURI)) {
      (prefixesByURI.get(namespaceURI)).add(prefix);
    } else {
      Set<String> set = new HashSet<String>();
      set.add(prefix);
      prefixesByURI.put(namespaceURI, set);
    }
  }
  public String getNamespaceURI(String prefix) {
    if (prefix == null)
      throw new IllegalArgumentException("prefix cannot be null");
    if (urisByPrefix.containsKey(prefix))
      return (String) urisByPrefix.get(prefix);
    else
      return XMLConstants.NULL_NS_URI;
  }
  public String getPrefix(String namespaceURI) {
    return (String) getPrefixes(namespaceURI).next();
  }
  public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null)
      throw new IllegalArgumentException("namespaceURI cannot be null");
    if (prefixesByURI.containsKey(namespaceURI)) {
      return ((Set) prefixesByURI.get(namespaceURI)).iterator();
    } else {
      return Collections.EMPTY_SET.iterator();
    }
  }
}