xml

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » xml 
OpenJDK: xml
License:The GNU General Public License (GPL)
URL:https://openjdk.dev.java.net
Description:
Package NameComment
javax.xml javax.xml

Defines core XML constants and functionality from the XML specifications.

The following core XML standards apply:

javax.xml.bind

Provides a runtime binding framework for client applications including unmarshalling, marshalling, and validation capabilities.

JAXBContext is the client-entry point to the runtime binding framework.

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
javax.xml.bind.annotation

Defines annotations for customizing Java program elements to XML Schema mapping.

Package Specification

The following table shows the JAXB mapping annotations that can be associated with each program element.

Program Element JAXB annotation
Package
XmlAccessorOrder
XmlAccessorType
XmlSchema
XmlSchemaType
XmlSchemaTypes
XmlJavaTypeAdapter
XmlJavaTypeAdapters
Class
XmlAccessorOrder
XmlAccessorType
XmlInlineBinaryData
XmlRootElement
XmlType
XmlJavaTypeAdapter
Enum type
XmlEnum
XmlEnumValue (enum constant only)
XmlRootElement
XmlType
XmlJavaTypeAdapter
JavaBean Property/field
XmlElement
XmlElements
XmlElementRef
XmlElementRefs
XmlElementWrapper
XmlAnyElement
XmlAttribute
XmlAnyAttribute
XmlTransient
XmlValue
XmlID
XmlIDREF
XmlList
XmlMixed
XmlMimeType
XmlAttachmentRef
XmlInlineBinaryData
XmlElementDecl (only on method)
XmlJavaTypeAdapter
Parameter
XmlList
XmlAttachmentRef
XmlMimeType
XmlJavaTypeAdapter

Terminology

JavaBean property and field: For the purposes of mapping, there is no semantic difference between a field and a JavaBean property. Thus, an annotation that can be applied to a JavaBean property can always be applied to a field. Hence in the Javadoc documentation, for brevity, the term JavaBean property or property is used to mean either JavaBean property or a field. Where required, both are explicitly mentioned.

top level class: For the purpose of mapping, there is no semantic difference between a top level class and a static nested class. Thus, an annotation that can be applied to a top level class, can always be applied to a nested static class. Hence in the Javadoc documentation, for brevity, the term "top level class" or just class is used to mean either a top level class or a nested static class.

mapping annotation:A JAXB 2.0 defined program annotation based on the JSR 175 programming annotation facility.

Common Usage Constraints

The following usage constraints are defined here since they apply to more than annotation:

  • For a property, a given annotation can be applied to either read or write property but not both.
  • A property name must be different from any other property name in any of the super classes of the class being mapped.
  • A mapped field name or the decapitalized name of a mapped property must be unique within a class.

Notations

Namespace prefixes

The following namespace prefixes are used in the XML Schema fragments in this package.

Prefix Namespace Notes
xs http://www.w3.org/2001/XMLSchema Namespace of XML Schema namespace
ref http://ws-i.org/profiles/basic/1.1/xsd Namespace for swaref schema component
xsi http://www.w3.org/2001/XMLSchema-instance XML Schema namespace for instances
@since JAXB 2.0

javax.xml.bind.annotation.adapters

{@link javax.xml.bind.annotation.adapters.XmlAdapter} and its spec-defined sub-classes to allow arbitrary Java classes to be used with JAXB.

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
javax.xml.bind.attachment

This package is implemented by a MIME-based package processor that enables the interpretation and creation of optimized binary data within an MIME-based package format.

Soap MTOM[1], XOP([2][3]) and WS-I AP[4] standardize approaches to optimized transmission of binary datatypes as an attachment. To optimally support these standards within a message passing environment, this package enables an integrated solution between a MIME-based package processor and JAXB unmarshall/marshal processes.

Package Specification

Related Standards

@since JAXB 2.0
javax.xml.bind.helpers

JAXB Provider Use Only: Provides partial default implementations for some of the javax.xml.bind interfaces.

JAXB Providers can extend these classes and implement the abstract methods.

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
javax.xml.bind.util

Useful client utility classes.

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
javax.xml.crypto Common classes for XML cryptography. This package includes common classes that are used to perform XML cryptographic operations, such as generating an XML signature or encrypting XML data.

Package Specification

Since:
1.6
javax.xml.crypto.dom DOM-specific classes for the {@link javax.xml.crypto} package. Only users who are using a DOM-based XML cryptographic implementations (ex: {@link javax.xml.crypto.dsig.XMLSignatureFactory XMLSignatureFactory} or {@link javax.xml.crypto.dsig.keyinfo.KeyInfoFactory}) should need to make direct use of this package.

Package Specification

Since:
1.6
javax.xml.crypto.dsig Classes for generating and validating XML digital signatures. This package includes classes that represent the core elements defined in the W3C XML digital signature specification: {@link javax.xml.crypto.dsig.XMLSignature XMLSignature}, {@link javax.xml.crypto.dsig.SignedInfo SignedInfo}, {@link javax.xml.crypto.dsig.CanonicalizationMethod CanonicalizationMethod}, {@link javax.xml.crypto.dsig.SignatureMethod SignatureMethod}, {@link javax.xml.crypto.dsig.Reference Reference}, {@link javax.xml.crypto.dsig.DigestMethod DigestMethod}, {@link javax.xml.crypto.dsig.XMLObject XMLObject}, {@link javax.xml.crypto.dsig.Manifest Manifest}, {@link javax.xml.crypto.dsig.SignatureProperties SignatureProperties}, and {@link javax.xml.crypto.dsig.SignatureProperty SignatureProperty}. KeyInfo types are defined in the {@link javax.xml.crypto.dsig.keyinfo} subpackage. {@link javax.xml.crypto.dsig.XMLSignatureFactory XMLSignatureFactory} is an abstract factory that creates {@link javax.xml.crypto.dsig.XMLSignature XMLSignature} objects from scratch or from a pre-existing XML representation, such as a DOM node. {@link javax.xml.crypto.dsig.TransformService} is a service provider interface for creating and plugging in implementations of transform and canonicalization algorithms.

Of primary significance in this package is the {@link javax.xml.crypto.dsig.XMLSignature XMLSignature} class, which allows you to sign and validate an XML digital signature.

Package Specification

Since:
1.6
javax.xml.crypto.dsig.dom DOM-specific classes for the {@link javax.xml.crypto.dsig} package. Only users who are using a DOM-based {@link javax.xml.crypto.dsig.XMLSignatureFactory XMLSignatureFactory} or {@link javax.xml.crypto.dsig.keyinfo.KeyInfoFactory} should need to make direct use of this package.

Package Specification

Since:
1.6
javax.xml.crypto.dsig.keyinfo Classes for parsing and processing {@link javax.xml.crypto.dsig.keyinfo.KeyInfo KeyInfo} elements and structures. KeyInfo is an optional element that enables the recipient(s) to obtain the key needed to validate an {@link javax.xml.crypto.dsig.XMLSignature XMLSignature}. KeyInfo may contain keys, names, certificates and other public key management information, such as in-band key distribution or key agreement data. This package contains classes representing types defined in the W3C specification for XML Signatures, such as {@link javax.xml.crypto.dsig.keyinfo.KeyName KeyName}, {@link javax.xml.crypto.dsig.keyinfo.KeyValue KeyValue}, {@link javax.xml.crypto.dsig.keyinfo.RetrievalMethod RetrievalMethod}, {@link javax.xml.crypto.dsig.keyinfo.X509Data X509Data}, {@link javax.xml.crypto.dsig.keyinfo.X509IssuerSerial X509IssuerSerial}, and {@link javax.xml.crypto.dsig.keyinfo.PGPData PGPData}. {@link javax.xml.crypto.dsig.keyinfo.KeyInfoFactory KeyInfoFactory} is an abstract factory that creates KeyInfo objects from scratch.

Package Specification

Since:
1.6
javax.xml.crypto.dsig.spec Parameter classes for XML digital signatures. This package contains interfaces and classes representing input parameters for the digest, signature, transform, or canonicalization algorithms used in the processing of XML signatures.

Package Specification

Since:
1.6
javax.xml.datatype javax.xml.xpath

XML/Java Type Mappings.

javax.xml.datatypeAPI provides XML/Java type mappings.

The following XML standards apply:


W3C XML Schema Data Type Java Data Type
xs:date {@link javax.xml.datatype.XMLGregorianCalendar}
xs:dateTime {@link javax.xml.datatype.XMLGregorianCalendar}
xs:duration {@link javax.xml.datatype.Duration}
xs:gDay {@link javax.xml.datatype.XMLGregorianCalendar}
xs:gMonth {@link javax.xml.datatype.XMLGregorianCalendar}
xs:gMonthDay {@link javax.xml.datatype.XMLGregorianCalendar}
xs:gYear {@link javax.xml.datatype.XMLGregorianCalendar}
xs:gYearMonth {@link javax.xml.datatype.XMLGregorianCalendar}
xs:time {@link javax.xml.datatype.XMLGregorianCalendar}

XQuery 1.0 and XPath 2.0 Data Model Java Data Type
xdt:dayTimeDuration {@link javax.xml.datatype.Duration}
xdt:yearMonthDuration {@link javax.xml.datatype.Duration}

W3C XML Schema data types that have a "natural" mapping to Java types are defined by JSR 31: Java™ Architecture for XML Binding (JAXB) Specification, Binding XML Schema to Java Representations. JAXB defined mappings for XML Schema built-in data types include:

  • xs:anySimpleType
  • xs:base64Binary
  • xs:boolean
  • xs:byte
  • xs:decimal
  • xs:double
  • xs:float
  • xs:hexBinary
  • xs:int
  • xs:integer
  • xs:long
  • xs:QName
  • xs:short
  • xs:string
  • xs:unsignedByte
  • xs:unsignedInt
  • xs:unsignedShort


javax.xml.namespace javax.xml.namespace

XML Namespace processing.

The following XML standards apply:

javax.xml.parsers javax.xml.parsers

Provides classes allowing the processing of XML documents. Two types of plugable parsers are supported:

  • SAX (Simple API for XML)
  • DOM (Document Object Model)
javax.xml.soap Provides the API for creating and building SOAP messages. This package is defined in the SOAP with Attachments API for JavaTM (SAAJ) 1.3 specification.

The API in the javax.xml.soap package allows you to do the following:

  • create a point-to-point connection to a specified endpoint
  • create a SOAP message
  • create an XML fragment
  • add content to the header of a SOAP message
  • add content to the body of a SOAP message
  • create attachment parts and add content to them
  • access/add/modify parts of a SOAP message
  • create/add/modify SOAP fault information
  • extract content from a SOAP message
  • send a SOAP request-response message

In addition the APIs in the javax.xml.soap package extend their counterparts in the org.w3c.dom package. This means that the SOAPPart of a SOAPMessage is also a DOM Level 2 Document, and can be manipulated as such by applications, tools and libraries that use DOM (see http://www.w3.org/DOM/ for more information). It is important to note that, while it is possible to use DOM APIs to add ordinary DOM nodes to a SAAJ tree, the SAAJ APIs are still required to return SAAJ types when examining or manipulating the tree. In order to accomplish this the SAAJ APIs (specifically {@link javax.xml.soap.SOAPElement#getChildElements()}) are allowed to silently replace objects that are incorrectly typed relative to SAAJ requirements with equivalent objects of the required type. These replacements must never cause the logical structure of the tree to change, so from the perspective of the DOM APIs the tree will remain unchanged. However, the physical composition of the tree will have changed so that references to the nodes that were replaced will refer to nodes that are no longer a part of the tree. The SAAJ APIs are not allowed to make these replacements if they are not required so the replacement objects will never subsequently be silently replaced by future calls to the SAAJ API.

What this means in practical terms is that an application that starts to use SAAJ APIs on a tree after manipulating it using DOM APIs must assume that the tree has been translated into an all SAAJ tree and that any references to objects within the tree that were obtained using DOM APIs are no longer valid. Switching from SAAJ APIs to DOM APIs is not allowed to cause invalid references and neither is using SAAJ APIs exclusively. It is only switching from using DOM APIs on a particular SAAJ tree to using SAAJ APIs that causes the risk of invalid references.

javax.xml.stream
javax.xml.stream.events
javax.xml.stream.util
javax.xml.transform javax.xml.transform

This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result. These interfaces have no dependencies on SAX or the DOM standard, and try to make as few assumptions as possible about the details of the source and result of a transformation. It achieves this by defining {@link javax.xml.transform.Source} and {@link javax.xml.transform.Result} interfaces.

To define concrete classes for the user, the API defines specializations of the interfaces found at the root level. These interfaces are found in {@link javax.xml.transform.sax}, {@link javax.xml.transform.dom}, and {@link javax.xml.transform.stream}.

Creating Objects

The API allows a concrete {@link javax.xml.transform.TransformerFactory} object to be created from the static function {@link javax.xml.transform.TransformerFactory#newInstance}.

Specification of Inputs and Outputs

This API defines two interface objects called {@link javax.xml.transform.Source} and {@link javax.xml.transform.Result}. In order to pass Source and Result objects to the interfaces, concrete classes must be used. Three concrete representations are defined for each of these objects: {@link javax.xml.transform.stream.StreamSource} and {@link javax.xml.transform.stream.StreamResult}, {@link javax.xml.transform.sax.SAXSource} and {@link javax.xml.transform.sax.SAXResult}, and {@link javax.xml.transform.dom.DOMSource} and {@link javax.xml.transform.dom.DOMResult}. Each of these objects defines a FEATURE string (which is i the form of a URL), which can be passed into {@link javax.xml.transform.TransformerFactory#getFeature} to see if the given type of Source or Result object is supported. For instance, to test if a DOMSource and a StreamResult is supported, you can apply the following test.


TransformerFactory tfactory = TransformerFactory.newInstance();
if (tfactory.getFeature(DOMSource.FEATURE) && tfactory.getFeature(StreamResult.FEATURE)) {
...
}

Qualified Name Representation

Namespaces present something of a problem area when dealing with XML objects. Qualified Names appear in XML markup as prefixed names. But the prefixes themselves do not hold identity. Rather, it is the URIs that they contextually map to that hold the identity. Therefore, when passing a Qualified Name like "xyz:foo" among Java programs, one must provide a means to map "xyz" to a namespace.

One solution has been to create a "QName" object that holds the namespace URI, as well as the prefix and local name, but this is not always an optimal solution, as when, for example, you want to use unique strings as keys in a dictionary object. Not having a string representation also makes it difficult to specify a namespaced identity outside the context of an XML document.

In order to pass namespaced values to transformations, for instance when setting a property or a parameter on a {@link javax.xml.transform.Transformer} object, this specification defines that a String "qname" object parameter be passed as two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the qname has a null URI, then the String object only contains the local name. An application can safely check for a non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>, then the Qualified Name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that the prefix is lost.

Result Tree Serialization

Serialization of the result tree to a stream can be controlled with the {@link javax.xml.transform.Transformer#setOutputProperties} and the {@link javax.xml.transform.Transformer#setOutputProperty} methods. These properties only apply to stream results, they have no effect when the result is a DOM tree or SAX event stream.

Strings that match the XSLT specification for xsl:output attributes can be referenced from the {@link javax.xml.transform.OutputKeys} class. Other strings can be specified as well. If the transformer does not recognize an output key, a {@link java.lang.IllegalArgumentException} is thrown, unless the key name is namespace qualified. Output key names that are namespace qualified are always allowed, although they may be ignored by some implementations.

If all that is desired is the simple identity transformation of a source to a result, then {@link javax.xml.transform.TransformerFactory} provides a {@link javax.xml.transform.TransformerFactory#newTransformer()} method with no arguments. This method creates a Transformer that effectively copies the source to the result. This method may be used to create a DOM from SAX events or to create an XML or HTML stream from a DOM or SAX events.

Exceptions and Error Reporting

The transformation API throw three types of specialized exceptions. A {@link javax.xml.transform.TransformerFactoryConfigurationError} is parallel to the {@link javax.xml.parsers.FactoryConfigurationError}, and is thrown when a configuration problem with the TransformerFactory exists. This error will typically be thrown when the transformation factory class specified with the "javax.xml.transform.TransformerFactory" system property cannot be found or instantiated.

A {@link javax.xml.transform.TransformerConfigurationException} may be thrown if for any reason a Transformer can not be created. A TransformerConfigurationException may be thrown if there is a syntax error in the transformation instructions, for example when {@link javax.xml.transform.TransformerFactory#newTransformer} is called.

{@link javax.xml.transform.TransformerException} is a general exception that occurs during the course of a transformation. A transformer exception may wrap another exception, and if any of the {@link javax.xml.transform.TransformerException#printStackTrace()} methods are called on it, it will produce a list of stack dumps, starting from the most recent. The transformer exception also provides a {@link javax.xml.transform.SourceLocator} object which indicates where in the source tree or transformation instructions the error occurred. {@link javax.xml.transform.TransformerException#getMessageAndLocation()} may be called to get an error message with location info, and {@link javax.xml.transform.TransformerException#getLocationAsString()} may be called to get just the location string.

Transformation warnings and errors are sent to an {@link javax.xml.transform.ErrorListener}, at which point the application may decide to report the error or warning, and may decide to throw an Exception for a non-fatal error. The ErrorListener may be set via {@link javax.xml.transform.TransformerFactory#setErrorListener} for reporting errors that have to do with syntax errors in the transformation instructions, or via {@link javax.xml.transform.Transformer#setErrorListener} to report errors that occur during the transformation. The ErrorListener on both objects will always be valid and non-null, whether set by the application or a default implementation provided by the processor. The default implementation provided by the processor will report all warnings and errors to System.err and does not throw any Exceptions. Applications are strongly encouraged to register and use ErrorListeners that insure proper behavior for warnings and errors.

Resolution of URIs within a transformation

The API provides a way for URIs referenced from within the stylesheet instructions or within the transformation to be resolved by the calling application. This can be done by creating a class that implements the {@link javax.xml.transform.URIResolver} interface, with its one method, {@link javax.xml.transform.URIResolver#resolve}, and use this class to set the URI resolution for the transformation instructions or transformation with {@link javax.xml.transform.TransformerFactory#setURIResolver} or {@link javax.xml.transform.Transformer#setURIResolver}. The URIResolver.resolve method takes two String arguments, the URI found in the stylesheet instructions or built as part of the transformation process, and the base URI against which the first argument will be made absolute if the absolute URI is required. The returned {@link javax.xml.transform.Source} object must be usable by the transformer, as specified in its implemented features.

javax.xml.transform.dom javax.xml.transform.dom

This package implements DOM-specific transformation APIs.

The {@link javax.xml.transform.dom.DOMSource} class allows the client of the implementation of this API to specify a DOM {@link org.w3c.dom.Node} as the source of the input tree. The model of how the Transformer deals with the DOM tree in terms of mismatches with the XSLT data model or other data models is beyond the scope of this document. Any of the nodes derived from {@link org.w3c.dom.Node} are legal input.

The {@link javax.xml.transform.dom.DOMResult} class allows a {@link org.w3c.dom.Node} to be specified to which result DOM nodes will be appended. If an output node is not specified, the transformer will use {@link javax.xml.parsers.DocumentBuilder#newDocument} to create an output {@link org.w3c.dom.Document} node. If a node is specified, it should be one of the following: {@link org.w3c.dom.Document}, {@link org.w3c.dom.Element}, or {@link org.w3c.dom.DocumentFragment}. Specification of any other node type is implementation dependent and undefined by this API. If the result is a {@link org.w3c.dom.Document}, the output of the transformation must have a single element root to set as the document element.

The {@link javax.xml.transform.dom.DOMLocator} node may be passed to {@link javax.xml.transform.TransformerException} objects, and retrieved by trying to cast the result of the {@link javax.xml.transform.TransformerException#getLocator()} method. The implementation has no responsibility to use a DOMLocator instead of a {@link javax.xml.transform.SourceLocator} (though line numbers and the like do not make much sense for a DOM), so the result of getLocator must always be tested with an instanceof.

javax.xml.transform.sax javax.xml.transform.sax

This package implements SAX2-specific transformation APIs. It provides classes which allow input from {@link org.xml.sax.ContentHandler} events, and also classes that produce org.xml.sax.ContentHandler events. It also provides methods to set the input source as an {@link org.xml.sax.XMLReader}, or to use a {@link org.xml.sax.InputSource} as the source. It also allows the creation of a {@link org.xml.sax.XMLFilter}, which enables transformations to "pull" from other transformations, and lets the transformer to be used polymorphically as an {@link org.xml.sax.XMLReader}.

The {@link javax.xml.transform.sax.SAXSource} class allows the setting of an {@link org.xml.sax.XMLReader} to be used for "pulling" parse events, and an {@link org.xml.sax.InputSource} that may be used to specify the SAX source.

The {@link javax.xml.transform.sax.SAXResult} class allows the setting of a {@link org.xml.sax.ContentHandler} to be the receiver of SAX2 events from the transformation.

The {@link javax.xml.transform.sax.SAXTransformerFactory} extends {@link javax.xml.transform.TransformerFactory} to provide factory methods for creating {@link javax.xml.transform.sax.TemplatesHandler}, {@link javax.xml.transform.sax.TransformerHandler}, and {@link org.xml.sax.XMLReader} instances.

To obtain a {@link javax.xml.transform.sax.SAXTransformerFactory}, the caller must cast the {@link javax.xml.transform.TransformerFactory} instance returned from {@link javax.xml.transform.TransformerFactory#newInstance}.

The {@link javax.xml.transform.sax.TransformerHandler} interface allows a transformation to be created from SAX2 parse events, which is a "push" model rather than the "pull" model that normally occurs for a transformation. Normal parse events are received through the {@link org.xml.sax.ContentHandler} interface, lexical events such as startCDATA and endCDATA are received through the {@link org.xml.sax.ext.LexicalHandler} interface, and events that signal the start or end of disabling output escaping are received via {@link org.xml.sax.ContentHandler#processingInstruction}, with the target parameter being {@link javax.xml.transform.Result#PI_DISABLE_OUTPUT_ESCAPING} and {@link javax.xml.transform.Result#PI_ENABLE_OUTPUT_ESCAPING}. If parameters, output properties, or other features need to be set on the Transformer handler, a {@link javax.xml.transform.Transformer} reference will need to be obtained from {@link javax.xml.transform.sax.TransformerHandler#getTransformer}, and the methods invoked from that reference.

The {@link javax.xml.transform.sax.TemplatesHandler} interface allows the creation of {@link javax.xml.transform.Templates} objects from SAX2 parse events. Once the {@link org.xml.sax.ContentHandler} events are complete, the Templates object may be obtained from {@link javax.xml.transform.sax.TemplatesHandler#getTemplates}. Note that {@link javax.xml.transform.sax.TemplatesHandler#setSystemId} should normally be called in order to establish a base system ID from which relative URLs may be resolved.

The {@link javax.xml.transform.sax.SAXTransformerFactory#newXMLFilter} method allows the creation of a {@link org.xml.sax.XMLFilter}, which encapsulates the SAX2 notion of a "pull" transformation. The following illustrates several transformations chained together. Each filter points to a parent {@link org.xml.sax.XMLReader}, and the final transformation is caused by invoking {@link org.xml.sax.XMLReader#parse} on the final reader in the chain.

javax.xml.transform.stax javax.xml.transform.stax

Provides for StAX-specific transformation APIs. TODO: better description(s).

Package Specification

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:

  • @see XMLStreamReader
  • @see XMLEventReader

@since 1.6

javax.xml.transform.stream javax.xml.transform.stream

This package implements stream- and URI- specific transformation APIs.

The {@link javax.xml.transform.stream.StreamSource} class provides methods for specifying {@link java.io.InputStream} input, {@link java.io.Reader} input, and URL input in the form of strings. Even if an input stream or reader is specified as the source, {@link javax.xml.transform.stream.StreamSource#setSystemId} should still be called, so that the transformer can know from where it should resolve relative URIs. The public identifier is always optional: if the application writer includes one, it will be provided as part of the {@link javax.xml.transform.SourceLocator} information.

The {@link javax.xml.transform.stream.StreamResult} class provides methods for specifying {@link java.io.OutputStream}, {@link java.io.Writer}, or an output system ID, as the output of the transformation result.

Normally streams should be used rather than readers or writers, for both the Source and Result, since readers and writers already have the encoding established to and from the internal Unicode format. However, there are times when it is useful to write to a character stream, such as when using a StringWriter in order to write to a String, or in the case of reading source XML from a StringReader.

javax.xml.validation javax.xml.validation

This package provides an API for validation of XML documents. Validation is the process of verifying that an XML document is an instance of a specified XML schema. An XML schema defines the content model (also called a grammar or vocabulary) that its instance documents will represent.

There are a number of popular technologies available for creating an XML schema. Some of the most popular include:

  • Document Type Definition (DTD) - XML's built-in schema language.
  • W3C XML Schema (WXS) - an object-oriented XML schema language. WXS also provides a type system for constraining the character data of an XML document. WXS is maintained by the World Wide Web Consortium (W3C) and is a W3C Recommendation (that is, a ratified W3C standard specification).
  • RELAX NG (RNG) - a pattern-based, user-friendly XML schema language. RNG schemas may also use types to constrain XML character data. RNG is maintained by the Organization for the Advancement of Structured Information Standards (OASIS) and is both an OASIS and an ISO (International Organization for Standardization) standard.
  • Schematron - a rules-based XML schema language. Whereas DTD, WXS, and RNG are designed to express the structure of a content model, Schematron is designed to enforce individual rules that are difficult or impossible to express with other schema languages. Schematron is intended to supplement a schema written in structural schema language such as the aforementioned. Schematron is in the process of becoming an ISO standard.

Previous versions of JAXP supported validation as a feature of an XML parser, represented by either a {@link javax.xml.parsers.SAXParser} or {@link javax.xml.parsers.DocumentBuilder} instance.

The JAXP validation API decouples the validation of an instance document from the parsing of an XML document. This is advantageous for several reasons, some of which are:

  • Support for additional schema langauges. As of JDK 1.5, the two most popular JAXP parser implementations, Crimson and Xerces, only support a subset of the available XML schema languages. The Validation API provides a standard mechanism through which applications may take of advantage of specialization validation libraries which support additional schema languages.
  • Easy runtime coupling of an XML instance and schema. Specifying the location of a schema to use for validation with JAXP parsers can be confusing. The Validation API makes this process simple (see example below).

Usage example. The following example demonstrates validating an XML document with the Validation API (for readability, some exception handling is not shown):

            
    // parse an XML document into a DOM tree
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = parser.parse(new File("instance.xml"));

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(new File("mySchema.xsd"));
    Schema schema = factory.newSchema(schemaFile);

    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();

    // validate the DOM tree
    try {
        validator.validate(new DOMSource(document));
    } catch (SAXException e) {
        // instance document is invalid!
    }

The JAXP parsing API has been integrated with the Validation API. Applications may create a {@link javax.xml.validation.Schema} with the validation API and associate it with a {@link javax.xml.parsers.DocumentBuilderFactory} or a {@link javax.xml.parsers.SAXParserFactory} instance by using the {@link javax.xml.parsers.DocumentBuilderFactory#setSchema(Schema)} and {@link javax.xml.parsers.SAXParserFactory#setSchema(Schema)} methods. You should not both set a schema and call setValidating(true) on a parser factory. The former technique will cause parsers to use the new validation API; the latter will cause parsers to use their own internal validation facilities. Turning on both of these options simultaneously will cause either redundant behavior or error conditions.

javax.xml.ws This package contains the core JAX-WS APIs.
javax.xml.ws.handler This package defines APIs for message handlers.
javax.xml.ws.handler.soap This package defines APIs for SOAP message handlers.
javax.xml.ws.http This package defines APIs specific to the HTTP binding.
javax.xml.ws.soap This package defines APIs specific to the SOAP binding.
javax.xml.ws.spi This package defines SPIs for JAX-WS 2.0.
javax.xml.xpath javax.xml.xpath

This package provides an object-model neutral API for the evaluation of XPath expressions and access to the evaluation environment.

The following XML standards apply:


XPath Overview

The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value. XPath is a W3C-defined language and an official W3C recommendation; the W3C hosts the XML Path Language (XPath) Version 1.0 specification.

XPath started in life in 1999 as a supplement to the XSLT and XPointer languages, but has more recently become popular as a stand-alone language, as a single XPath expression can be used to replace many lines of DOM API code.

XPath Expressions

An XPath expression is composed of a location path and one or more optional predicates. Expressions may also include XPath variables.

The following is an example of a simple XPath expression:

/foo/bar

This example would select the <bar> element in an XML document such as the following:

<foo>
<bar/>
</foo>

The expression /foo/bar is an example of a location path. While XPath location paths resemble Unix-style file system paths, an important distinction is that XPath expressions return all nodes that match the expression. Thus, all three <bar> elements in the following document would be selected by the /foo/bar expression:

<foo>
<bar/>
<bar/>
<bar/>
</foo>

A special location path operator, //, selects nodes at any depth in an XML document. The following example selects all <bar> elements regardless of their location in a document:

//bar

A wildcard operator, *, causes all element nodes to be selected. The following example selects all children elements of a <foo> element:

/foo/*

In addition to element nodes, XPath location paths may also address attribute nodes, text nodes, comment nodes, and processing instruction nodes. The following table gives examples of location paths for each of these node types:

Location Path Description
/foo/bar/@id Selects the attribute id of the <bar> element
/foo/bar/text() Selects the text nodes of the <bar> element. No distinction is made between escaped and non-escaped character data.
/foo/bar/comment() Selects all comment nodes contained in the <bar> element.
/foo/bar/processing-instruction() Selects all processing-instruction nodes contained in the <bar> element.

Predicates allow for refining the nodes selected by an XPath location path. Predicates are of the form [expression]. The following example selects all <foo> elements that contain an include attribute with the value of true:

//foo[@include='true']

Predicates may be appended to each other to further refine an expression, such as:

//foo[@include='true'][@mode='bar']

Using the XPath API

The following example demonstrates using the XPath API to select one or more nodes from an XML document:

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget";
InputSource inputSource = new InputSource("widgets.xml");
NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);

XPath Expressions and Types

While XPath expressions select nodes in the XML document, the XPath API allows the selected nodes to be coalesced into one of the following other data types:

  • Boolean
  • Number
  • String

The desired return type is specified by a {@link javax.xml.namespace.QName} parameter in method call used to evaluate the expression, which is either a call to XPathExpression.evalute(...) or to one of the XPath.evaluate(...) convenience methods. The allowed QName values are specified as constants in the {@link javax.xml.xpath.XPathConstants} class; they are:

  • {@link javax.xml.xpath.XPathConstants#NODESET}
  • {@link javax.xml.xpath.XPathConstants#NODE}
  • {@link javax.xml.xpath.XPathConstants#STRING}
  • {@link javax.xml.xpath.XPathConstants#BOOLEAN}
  • {@link javax.xml.xpath.XPathConstants#NUMBER}

When a Boolean return type is requested, Boolean.TRUE is returned if one or more nodes were selected; otherwise, Boolean.FALSE is returned.

The String return type is a convenience for retrieving the character data from a text node, attribute node, comment node, or processing-instruction node. When used on an element node, the value of the child text nodes is returned.

The Number return type attempts to coalesce the text of a node to a double data type.

XPath Context

XPath location paths may be relative to a particular node in the document, known as the context. Consider the following XML document:

<widgets>
<widget>
<manufacturer/>
<dimensions/>
</widget>
</widgets>

The <widget> element can be selected with the following XPath API code:

// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new File("/widgets.xml"));

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget";
Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);

With a reference to the <widget> element, a relative XPath expression can now written to select the <manufacturer> child element:

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "manufacturer";
Node manufacturerNode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);
org.xml.sax

This package provides the core SAX APIs. Some SAX1 APIs are deprecated to encourage integration of namespace-awareness into designs of new applications and into maintenance of existing infrastructure.

See http://www.saxproject.org for more information about SAX.

SAX2 Standard Feature Flags

One of the essential characteristics of SAX2 is that it added feature flags which can be used to examine and perhaps modify parser modes, in particular modes such as validation. Since features are identified by (absolute) URIs, anyone can define such features. Currently defined standard feature URIs have the prefix http://xml.org/sax/features/ before an identifier such as validation. Turn features on or off using setFeature. Those standard identifiers are:

Feature ID Access Default Description
external-general-entities read/write unspecified Reports whether this parser processes external general entities; always true if validating.
external-parameter-entities read/write unspecified Reports whether this parser processes external parameter entities; always true if validating.
is-standalone (parsing) read-only, (not parsing) none not applicable May be examined only during a parse, after the startDocument() callback has been completed; read-only. The value is true if the document specified standalone="yes" in its XML declaration, and otherwise is false.
lexical-handler/parameter-entities read/write unspecified A value of "true" indicates that the LexicalHandler will report the beginning and end of parameter entities.
namespaces read/write true A value of "true" indicates namespace URIs and unprefixed local names for element and attribute names will be available.
namespace-prefixes read/write false A value of "true" indicates that XML qualified names (with prefixes) and attributes (including xmlns* attributes) will be available.
resolve-dtd-uris read/write true A value of "true" indicates that system IDs in declarations will be absolutized (relative to their base URIs) before reporting. (That is the default behavior for all SAX2 XML parsers.) A value of "false" indicates those IDs will not be absolutized; parsers will provide the base URI from Locator.getSystemId(). This applies to system IDs passed in
  • DTDHandler.notationDecl(),
  • DTDHandler.unparsedEntityDecl(), and
  • DeclHandler.externalEntityDecl().
It does not apply to EntityResolver.resolveEntity(), which is not used to report declarations, or to LexicalHandler.startDTD(), which already provides the non-absolutized URI.
string-interning read/write unspecified Has a value of "true" if all XML names (for elements, prefixes, attributes, entities, notations, and local names), as well as Namespace URIs, will have been interned using java.lang.String.intern. This supports fast testing of equality/inequality against string constants, rather than forcing slower calls to String.equals().
unicode-normalization-checking read/write false Controls whether the parser reports Unicode normalization errors as described in section 2.13 and Appendix B of the XML 1.1 Recommendation. If true, Unicode normalization errors are reported using the ErrorHandler.error() callback. Such errors are not fatal in themselves (though, obviously, other Unicode-related encoding errors may be).
use-attributes2 read-only not applicable Returns "true" if the Attributes objects passed by this parser in ContentHandler.startElement() implement the org.xml.sax.ext.Attributes2 interface. That interface exposes additional DTD-related information, such as whether the attribute was specified in the source text rather than defaulted.
use-locator2 read-only not applicable Returns "true" if the Locator objects passed by this parser in ContentHandler.setDocumentLocator() implement the org.xml.sax.ext.Locator2 interface. That interface exposes additional entity information, such as the character encoding and XML version used.
use-entity-resolver2 read/write true Returns "true" if, when setEntityResolver is given an object implementing the org.xml.sax.ext.EntityResolver2 interface, those new methods will be used. Returns "false" to indicate that those methods will not be used.
validation read/write unspecified Controls whether the parser is reporting all validity errors; if true, all external entities will be read.
xmlns-uris read/write false Controls whether, when the namespace-prefixes feature is set, the parser treats namespace declaration attributes as being in the http://www.w3.org/2000/xmlns/ namespace. By default, SAX2 conforms to the original "Namespaces in XML" Recommendation, which explicitly states that such attributes are not in any namespace. Setting this optional flag to "true" makes the SAX2 events conform to a later backwards-incompatible revision of that recommendation, placing those attributes in a namespace.
xml-1.1 read-only not applicable Returns "true" if the parser supports both XML 1.1 and XML 1.0. Returns "false" if the parser supports only XML 1.0.

Support for the default values of the namespaces and namespace-prefixes properties is required. Support for any other feature flags is entirely optional.

For default values not specified by SAX2, each XMLReader implementation specifies its default, or may choose not to expose the feature flag. Unless otherwise specified here, implementations may support changing current values of these standard feature flags, but not while parsing.

SAX2 Standard Handler and Property IDs

For parser interface characteristics that are described as objects, a separate namespace is defined. The objects in this namespace are again identified by URI, and the standard property URIs have the prefix http://xml.org/sax/properties/ before an identifier such as lexical-handler or dom-node. Manage those properties using setProperty(). Those identifiers are:

Property ID Description
declaration-handler Used to see most DTD declarations except those treated as lexical ("document element name is ...") or which are mandatory for all SAX parsers (DTDHandler). The Object must implement org.xml.sax.ext.DeclHandler.
document-xml-version May be examined only during a parse, after the startDocument() callback has been completed; read-only. This property is a literal string describing the actual XML version of the document, such as "1.0" or "1.1".
dom-node For "DOM Walker" style parsers, which ignore their parser.parse() parameters, this is used to specify the DOM (sub)tree being walked by the parser. The Object must implement the org.w3c.dom.Node interface.
lexical-handler Used to see some syntax events that are essential in some applications: comments, CDATA delimiters, selected general entity inclusions, and the start and end of the DTD (and declaration of document element name). The Object must implement org.xml.sax.ext.LexicalHandler.
xml-string Readable only during a parser callback, this exposes a TBS chunk of characters responsible for the current event.

All of these standard properties are optional; XMLReader implementations need not support them.

org.xml.sax.ext

This package contains interfaces to SAX2 facilities that conformant SAX drivers won't necessarily support.

See http://www.saxproject.org for more information about SAX.

This package is independent of the SAX2 core, though the functionality exposed generally needs to be implemented within a parser core. That independence has several consequences:

  • SAX2 drivers are not required to recognize these handlers.
  • You cannot assume that the class files will be present in every SAX2 installation.
  • This package may be updated independently of SAX2 (i.e. new handlers and classes may be added without updating SAX2 itself).
  • The new handlers are not implemented by the SAX2 org.xml.sax.helpers.DefaultHandler or org.xml.sax.helpers.XMLFilterImpl classes. You can subclass these if you need such behavior, or use the helper classes found here.
  • The handlers need to be registered differently than core SAX2 handlers.

This package, SAX2-ext, is a standardized extension to SAX2. It is designed both to allow SAX parsers to pass certain types of information to applications, and to serve as a simple model for other SAX2 parser extension packages. Not all such extension packages should need to be recognized directly by parsers, however. As an example, most validation systems can be cleanly layered on top of parsers supporting the standardized SAX2 interfaces.

org.xml.sax.helpers

This package contains "helper" classes, including support for bootstrapping SAX-based applications.

See http://www.saxproject.org for more information about SAX.

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.