JSR 206 Java API for XML Processing (JAXP) 1.3

Jeff Suttor Norman Walsh Kohsuke Kawaguchi

JSR 206 Java™ API for XML Processing (JAXP) 1.3 by Jeff Suttor, Norman Walsh, and Kohsuke Kawaguchi Copyright © 2004 Sun Microsystems, Inc.

Final 1.0.0 The JSR 206 Java™ API for XML Processing (JAXP) 1.3 Expert Group would like to thank participants in the Java Community that are reviewing this Java Specification Request. All comments, feedback and guidance from the Java Community is appreciated. Please submit comments to .

Specification: JSR-206: Java™ API for XML Processing (JAXP) 1.3 Specification ("Specification"), Status: Final Release, Release: September 1, 2004 Copyright 2004 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

NOTICE; LIMITED LICENSE GRANTS Sun Microsystems, Inc. ("Sun") hereby grants you a fully-paid, non-exclusive, non-transferable, worldwide, limited license (without the right to sublicense), under the Sun’s applicable intellectual property rights to view, download, use and reproduce the Specification only for the purpose of internal evaluation, which shall be understood to include developing applications intended to run on an implementation of the Specification provided that such applications do not themselves implement any portion(s) of the Specification. Sun also grants you a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, limited license (without the right to sublicense) under any applicable copyrights or patent rights it may have in the Specification to create and/or distribute an Independent Implementation of the Specification that: (i) fully implements the Spec(s) including all its required interfaces and functionality; (ii) does not modify, subset, superset or otherwise extend the Licensor Name Space, or include any public or protected packages, classes, Java interfaces, fields or methods within the Licensor Name Space other than those required/authorized by the Specification or Specifications being implemented; and (iii) passes the TCK (including satisfying the requirements of the applicable TCK Users Guide) for such Specification. The foregoing license is expressly conditioned on your not acting outside its scope. No license is granted hereunder for any other purpose. You need not include limitations (i)-(iii) from the previous paragraph or any other particular "pass through" requirements in any license You grant concerning the use of your Independent Implementation or products derived from it. However, except with respect to implementations of the Spe  cification (and products derived from them) that satisfy limitations (i)-(iii) from the previous paragraph, You may neither: (a) grant or otherwise pass through to your licensees any licenses under Sun’s applicable intellectual property rights; nor (b) authorize your licensees to make any claims concerning their implementation’s compliance with the Spec in question. For the purposes of this Agreement: "Independent Implementation" shall mean an implementation of the Specification that neither derives from any of Sun’s source code or binary code materials nor, except with an appropriate and separate license from Sun, includes any of Sun’s source code or binary code materials; and "Licensor Name Space" shall mean the public class or interface declarations whose names begin with "java", "javax", "com.sun" or their equivalents in any subsequent naming convention adopted by Sun through the Java Community Process, or any recognized successors or replacements thereof. This Agreement will terminate immediately without notice from Sun if you fail to comply with any material provision of or act outside the scope of the licenses granted above.

TRADEMARKS No right, title, or interest in or to any trademarks, service marks, or trade names of Sun, Sun’s licensors, Specification Lead or the Specification Lead’s licensors is granted hereunder. Sun, Sun Microsystems, the Sun logo, Java, J2SE, J2EE, J2ME, Java Compatible, the Java Compatible Logo, and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

DISCLAIMER OF WARRANTIES THE SPECIFICATION IS PROVIDED "AS IS".  SUN MAKES NO REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT, THAT THE CONTENTS OF THE SPECIFICATION ARE SUITABLE FOR ANY PURPOSE OR THAT ANY PRACTICE

Final 1.0.0

OR IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER RIGHTS.  This document does not represent any commitment to release or implement any portion of the Specification in any product. THE SPECIFICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION THEREIN; THESE CHANGES WILL BE INCORPORATED INTO NEW VERSIONS OF THE SPECIFIC  ATION, IF ANY.  SUN MAY MAKE IMPROVEMENTS AND/OR CHANGES TO THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THE SPECIFICATION AT ANY TIME.  Any use of such changes in the Specification will be governed by the then-current license for the ap  plicable version of the Specification.

LIMITATION OF LIABILITY TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES, IN  CLUDING WITHOUT LIMITATION, LOST REVENUE, PROFITS OR DATA, OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCID  ENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF OR RELATED TO ANY FURNISHING, PRACTICING, MODIFYING OR ANY USE OF THE SPECIFICATION, EVEN IF SUN AND/OR ITS LICENSORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. You will indemnify, hold harmless, and defend Sun and its licensors from any claims arising or resulting from: (i) your use of the Specification; (ii) the use or distribution of your Java application, applet and/or clean room implementation; and/or (iii) any claims that later versions or releases of any Specification furnished to you are incompatible with the Specification provided to you under this license.

RESTRICTED RIGHTS LEGEND U.S. Government: If this Specification is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government’s rights in the Specification and accompanying documentation shall be only as set forth in this license; this is in accordance with 48 C.F.R. 227.7201 through 227.7202-4 (for Department of Defense (DoD) acquisitions) and with 48 C.F.R. 2.101 and 12.212 (for non-DoD acquisitions).

REPORT You may wish to report any ambiguities, inconsistencies or inaccuracies you may find in connection with your use of the Specification ("Feedback"). To the extent that you provide Sun with any Feedback, you hereby: (i) agree that such Feedback is provided on a non-proprietary and non-confidential basis, and (ii) grant Sun a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable license, with the right to sublicense through multiple levels of sublicensees, to incorporate, disclose, and use without limitation the Feedback for any purpose related to the Specification and future versions, implementations, and test suites thereof.

GENERAL TERMS Any action related to this Agreement will be governed by California law and controlling U.S. federal law. The U.N. Convention for the International Sale of Goods and the choice of law rules of any jurisdiction will not apply. The Specification is subject to U.S. export control laws and may be subject to export or import regulations in other countries. Licensee agrees to comply strictly with all such laws and regulations and acknowledges that it has the responsibility to obtain such licenses to export, re-export or import as may be required after delivery to Licensee. Neither party may assign or otherwise transfer any of its rights or obligations under this Agreement, without the prior written consent of the other party, except that Sun may assign this Agreement to an affiliated company. This Agreement is the parties’ entire agreement relating to its subject matter. It supersedes all prior or contemporaneous oral or written communic  ations, proposals, conditions, representations and warranties and prevails over any conflicting or additional terms of any quote, order, acknowledgment, or other communication between the parties relating to its subject matter during the term of this Agreement. No modification to this Agreement will be binding, unless in writing and signed by an authorized representative of each party. (Sun.CfcsSpec.license.11.14.2003)

Final 1.0.0

Table of Contents 1. Overview ........................................................................................................................................ 1 What is XML? ............................................................................................................................ 1 XML and the Java Platform ........................................................................................................... 1 About This Specification ............................................................................................................... 1 Who Should Read This Document .................................................................................................. 2 Report and Contact ...................................................................................................................... 2 Development of This Specification .................................................................................................. 2 Acknowledgments ....................................................................................................................... 3 2. Endorsed Specifications ..................................................................................................................... 4 Extensible Markup Language (XML) .............................................................................................. 4 Namespaces in XML .................................................................................................................... 4 XML Schema ............................................................................................................................. 4 XSL Transformations (XSLT) ........................................................................................................ 5 XML Path Language (XPath) ......................................................................................................... 5 XML Inclusions (XInclude) ........................................................................................................... 5 Document Object Model (DOM) Level 3 ......................................................................................... 5 Simple API for XML (SAX) .......................................................................................................... 6 3. Plugability Layer .............................................................................................................................. 7 SAX Plugability .......................................................................................................................... 7 Examples ........................................................................................................................... 7 DOM Plugability ......................................................................................................................... 8 Reliance on SAX API ........................................................................................................... 9 Examples ........................................................................................................................... 9 XSLT Plugability ....................................................................................................................... 10 Examples ......................................................................................................................... 10 XPath Plugability ....................................................................................................................... 15 Examples ......................................................................................................................... 16 Validation Plugability ................................................................................................................. 16 Thread Safety ............................................................................................................................ 17 Properties For Enabling Schema Validation ..................................................................................... 17 Samples Using the Properties ............................................................................................... 20 Recommended Implementation of Properties ................................................................................... 20 4. Conformance Requirements .............................................................................................................. 21 5. XML Inclusions (XInclude) .............................................................................................................. 22 What is XML Inclusions (XInclude) .............................................................................................. 22 Implementation Required by JSR 206 Java API for XML Processing (JAXP) 1.3 ................................... 22 6. JSR 206 Java API for XML Processing (JAXP) 1.3 Specification and Implementation Version Information ...... 23 JSR 206 Java API for XML Processing (JAXP) 1.3 Specification Version Information ............................. 23 JSR 206 Java API for XML Processing (JAXP) 1.3 Implementation Version Information ......................... 24 7. Package javax.xml.parsers ................................................................................................................ 25 Class DocumentBuilder ............................................................................................................... 25 Synopsis .......................................................................................................................... 25 Members .......................................................................................................................... 26 Class DocumentBuilderFactory .................................................................................................... 30 Synopsis .......................................................................................................................... 30 Members .......................................................................................................................... 31 Class SAXParser ....................................................................................................................... 38 Synopsis .......................................................................................................................... 39 Members .......................................................................................................................... 40 Class SAXParserFactory ............................................................................................................. 47 Synopsis .......................................................................................................................... 47

iv

Final 1.0.0

JSR 206 Java API for XML Processing (JAXP) 1.3 Members .......................................................................................................................... Exception ParserConfigurationException ........................................................................................ Synopsis .......................................................................................................................... Members .......................................................................................................................... Error FactoryConfigurationError ................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... 8. Package javax.xml.transform ............................................................................................................ Creating Objects ........................................................................................................................ Specification of Inputs and Outputs ....................................................................................... Class OutputKeys ...................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Class Transformer ...................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Class TransformerFactory ............................................................................................................ Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface ErrorListener ................................................................................................................ Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface Result ......................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface Source ......................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface SourceLocator .............................................................................................................. Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface Templates .................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface URIResolver ................................................................................................................ Synopsis .......................................................................................................................... Members .......................................................................................................................... Exception TransformerConfigurationException ................................................................................ Synopsis .......................................................................................................................... Members .......................................................................................................................... Exception TransformerException .................................................................................................. Synopsis .......................................................................................................................... Members .......................................................................................................................... Error TransformerFactoryConfigurationError .................................................................................. Synopsis .......................................................................................................................... Members .......................................................................................................................... 9. Package javax.xml.transform.dom ...................................................................................................... Class DOMResult ...................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Class DOMSource ..................................................................................................................... Synopsis .......................................................................................................................... Members .......................................................................................................................... Interface DOMLocator ................................................................................................................

v

Final 1.0.0

48 53 53 54 54 54 55 57 57 57 59 59 59 62 62 63 68 68 69 74 74 74 76 76 76 77 77 77 78 78 78 79 79 79 80 80 81 81 81 82 83 83 84 87 88 88 90 90 90 91 95 95 96 97

JSR 206 Java API for XML Processing (JAXP) 1.3 Synopsis .......................................................................................................................... 97 Members .......................................................................................................................... 97 10. Package javax.xml.transform.sax ..................................................................................................... 98 Class SAXResult ....................................................................................................................... 98 Synopsis .......................................................................................................................... 99 Members .......................................................................................................................... 99 Class SAXSource ..................................................................................................................... 101 Synopsis ......................................................................................................................... 101 Members ........................................................................................................................ 101 Class SAXTransformerFactory ................................................................................................... 104 Synopsis ......................................................................................................................... 104 Members ........................................................................................................................ 104 Interface TemplatesHandler ........................................................................................................ 107 Synopsis ......................................................................................................................... 107 Members ........................................................................................................................ 107 Interface TransformerHandler ..................................................................................................... 108 Synopsis ......................................................................................................................... 108 Members ........................................................................................................................ 108 11. Package javax.xml.transform.stream ............................................................................................... 110 Class StreamResult ................................................................................................................... 110 Synopsis ......................................................................................................................... 110 Members ........................................................................................................................ 111 Class StreamSource .................................................................................................................. 113 Synopsis ......................................................................................................................... 113 Members ........................................................................................................................ 114 12. Package javax.xml.namespace ....................................................................................................... 118 Class QName .......................................................................................................................... 118 Synopsis ......................................................................................................................... 118 Members ........................................................................................................................ 119 Interface NamespaceContext ...................................................................................................... 123 Synopsis ......................................................................................................................... 123 Members ........................................................................................................................ 124 13. Package javax.xml.xpath ............................................................................................................... 127 XPath Overview ....................................................................................................................... 127 XPath Expressions ............................................................................................................ 127 Class XPathConstants ............................................................................................................... 130 Synopsis ......................................................................................................................... 130 Members ........................................................................................................................ 130 Class XPathFactory .................................................................................................................. 131 Synopsis ......................................................................................................................... 131 Members ........................................................................................................................ 132 Interface XPath ........................................................................................................................ 136 Synopsis ......................................................................................................................... 137 Members ........................................................................................................................ 138 Interface XPathExpression ......................................................................................................... 143 Synopsis ......................................................................................................................... 143 Members ........................................................................................................................ 144 Interface XPathFunction ............................................................................................................ 146 Synopsis ......................................................................................................................... 146 Members ........................................................................................................................ 147 Interface XPathFunctionResolver ................................................................................................ 147 Synopsis ......................................................................................................................... 147 Members ........................................................................................................................ 148 Interface XPathVariableResolver ................................................................................................. 148

vi

Final 1.0.0

JSR 206 Java API for XML Processing (JAXP) 1.3 Synopsis ......................................................................................................................... Members ........................................................................................................................ Exception XPathException ......................................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Exception XPathExpressionException .......................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Exception XPathFactoryConfigurationException ............................................................................ Synopsis ......................................................................................................................... Members ........................................................................................................................ Exception XPathFunctionException ............................................................................................. Synopsis ......................................................................................................................... Members ........................................................................................................................ 14. Package javax.xml.validation ......................................................................................................... Class Schema .......................................................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Class SchemaFactory ................................................................................................................ Schema Language ............................................................................................................ Synopsis ......................................................................................................................... Members ........................................................................................................................ Class TypeInfoProvider ............................................................................................................. Synopsis ......................................................................................................................... Members ........................................................................................................................ Class Validator ......................................................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Class ValidatorHandler .............................................................................................................. Recognized Properties and Features ..................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ 15. Package javax.xml.datatype ........................................................................................................... Class DatatypeConstants ............................................................................................................ Synopsis ......................................................................................................................... Members ........................................................................................................................ Class DatatypeConstants.Field .................................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Class DatatypeFactory ............................................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Class Duration ......................................................................................................................... Order relationship ............................................................................................................ Synopsis ......................................................................................................................... Members ........................................................................................................................ Class XMLGregorianCalendar .................................................................................................... Synopsis ......................................................................................................................... Members ........................................................................................................................ Exception DatatypeConfigurationException .................................................................................. Synopsis ......................................................................................................................... Members ........................................................................................................................ 16. Package javax.xml ....................................................................................................................... Class XMLConstants ................................................................................................................

vii

Final 1.0.0

148 149 149 149 150 151 151 151 152 152 153 153 153 154 155 156 156 157 157 158 158 159 169 169 170 172 173 174 180 181 181 182 189 190 190 191 195 195 195 195 196 198 213 214 214 216 227 230 232 246 246 247 248 248

JSR 206 Java API for XML Processing (JAXP) 1.3 Synopsis ......................................................................................................................... Members ........................................................................................................................ 17. Colophon ................................................................................................................................... Talk the Talk, Walk the Walk ......................................................................................................

viii

Final 1.0.0

248 248 252 252

List of Tables 6.1. JSR 206 Java API for XML Processing (JAXP) 1.3 Specification Version Information ............................... 23 17.1. XML Usage Conventions ........................................................................................................... 252

ix

Final 1.0.0

x

Final 1.0.0

Chapter 1. Overview What is XML? XML is the meta language defined by the World Wide Web Consortium (W3C) that can be used to describe a broad range of hierarchical mark up languages. It is a set of rules, guidelines, and conventions for describing structured data in a plain text, editable file. Using a text format instead of a binary format allows the programmer or even an end user to look at or utilize the data without relying on the program that produced it. However the primary producer and consumer of XML data is the computer program and not the end-user. Like HTML, XML makes use of tags and attributes. Tags are words bracketed by the "<" and ">" characters and attributes are strings of the form ’name="value"’ that are inside of tags. While HTML specifies what each tag and attribute means, as well as their presentation attributes in a browser, XML uses tags only to delimit pieces of data and leaves the interpretation of the data to the application that uses it. In other words, XML defines only the structure of the document and does not define any of the presentation semantics of that document. Development of XML started in 1996 leading to a W3C Recommendation in February of 1998. However, the technology is not entirely new. It is based on SGML (Standard Generalized Markup Language) which was developed in the early 1980’s and became an ISO standard in 1986. SGML has been widely used for large documentation projects and there is a large community that has experience working with SGML. The designers of XML took the best parts of SGML, used their experience as a guide and produced a technology that is just as powerful as SGML, but much simpler and easier to use. XML-based documents can be used in a wide variety of applications including vertical markets, e-commerce, businessto-business communication, and enterprise application messaging.

XML and the Java™ Platform In many ways, XML and the Java Platform are a partnership made in heaven. XML defines a cross platform data format and Java provides a standard cross platform programming platform. Together, XML and Java technologies allow pro  grammers to apply Write Once, Run Anywhere™ fundamentals to the processing of data and documents generated by both Java based programs and non-Java based programs.

About This Specification This document describes the Java API for XML Processing, Version 1.3. This version of the specification introduces basic support for parsing and manipulating XML documents through a standardized set of Java Platform APIs. When this specification is final there will be a Reference Implementation which will demonstrate the capabilities of this API and will provide an operational definition of the specification. A Technology Compatibility Kit (TCK) will also be available that will verify whether an implementation of this specification is compliant. These are required as per the Java Community Process 2.5 (JCP 2.5).

Note API references are accompanied by a small-font subscript that gives the page on which the API is defined. For example: newDocumentBuilder33

1

Final 1.0.0

Overview

Who Should Read This Document This specification is intended for use by: •

Parser Developers wishing to implement this version of the specification in their parser.



Application Developers who use the APIs described in this specification and wish to have a more complete under  standing of the API.

This specification is not a tutorial or a user’s guide to XML, DOM, SAX or XSLT. Familiarity with these technologies and specifications on the part of the reader is assumed.

Report and Contact Your comments on this specification are welcome and appreciated. Without your comments, the specifications developed under the auspices of the Java Community Process would not serve your needs as well. To comment on this specification, please send email to . You can stay current with Sun’s Java Platform related activities, as well as information on our and mailing lists, at our website [http://java.sun.com/xml/jaxp].

Development of This Specification This specification was developed in accordance with the Java Community Process [http://www.jcp.org] 2.5. It was developed under the authorization of Java Specification Request 206 [http://jcp.org/en/jsr/detail?id=206]. The expert group who contributed to this specification is composed of individuals from a number of companies. These individuals are: •

Jeff Suttor (Specification Lead), Sun Microsystems, Inc.



Norm Walsh (Specification Lead), Sun Microsystems, Inc.



Kohsuke Kawaguchi (Markup Geek), Sun Microsystems, Inc.



Ben Galbraith



Neil Graham, IBM



Phil Hanna, SAS Institute Inc.



Todd Karakashian, bea



K. Karun, Oracle



Dongeun Kim, Tmax Soft, Inc.



Harish Krishnaswamy, Novell, Inc.



Miles Sabin



Vladimir Savchenko, SAP AG



Ilene Seelemann, IBM

2

Final 1.0.0

Overview



Henry Zongaro, IBM

We would like to acknowledge that a lot of the grammar caching work introduced in this version of the specification was derived from the work being done under the Xerces project at Apache.

Acknowledgments Many individuals and companies have given their time and talents to make this specification, or the specifications that this specification relies upon, a reality. The authors of this specification would like to thank (in no particular order): •

David Brownell, David Megginson and the XML-DEV community who developed the SAX API



The W3C DOM Working Group chaired by Philippe Le Hégaret



The Apache Software Foundation [http://apache.org/], for Xerces and Xalan



Michael Kay, Saxonica [http://www.saxonica.com/]



Elliotte Rusty Harold, Cafe con Leche XML News and Resources [http://www.cafeconleche.org/], Cafe au Lait Java News and Resources [http://www.cafeaulait.org/]



Han Ming Ong, Apple



Eduardo Pelegri-Lopart, Tom Kincaid, Connie Weiss, Gopal Sharma, Neeraj Bajaj, K. Venugopal, Arun Yadav, Ramesh Mandava, Bhakti Mehta, Prasad Subramanian, Todd Miller, Joesph Fialli, and Rajiv Mordani all of whom work at Sun Microsystems, Inc. and whose talents have all reflected upon the development of this API.



Margaret L. Wade for allowing it all to be true.

3

Final 1.0.0

Chapter 2. Endorsed Specifications This specification endorses and builds upon several external specifications. Each specification endorsed by this document is called out together with the exact version of the specification and its publicly accessible location. All of these standards have conformance tests provided in the Technology Compatibility Kit available for this specification.

Extensible Markup Language (XML) This specification supports Extensible Markup Language (XML) 1.1 [http://www.w3.org/TR/xml11], Extensible Markup Language (XML) 1.0 (Second Edition) [http://www.w3.org/TR/REC-xml] and Extensible Markup Language (XML) 1.0 (Second Edition) Errata [http://www.w3.org/XML/xml-V10-2e-errata] XML is a product of the W3C XML Activity [http://www.w3.org/XML/]. This specification includes by reference Extensible Markup Language (XML) 1.1, Extensible Markup Language (XML) 1.0 (Second Edition) and Extensible Markup Language (XML) 1.0 (Second Edition) Errata in their entirety for the purposes of defining XML in the APIs defined herein.

A Note about XML Versions XML 1.0 and XML 1.1 are not completely interchangable. Developers working in environments where a mixture of versions may exist must consider carefully how serialization and transformation may interact with XML versions.

Namespaces in XML This specification supports Namespaces in XML 1.1. [http://www.w3.org/TR/xml-names11/], Namespaces in XML 1.0 [http://www.w3.org/TR/REC-xml-names] and Namespaces in XML 1.0 Errata [http://www.w3.org/XML/xml-names-19990114-errata]. Namespaces in XML is a product of the W3C XML Activity [http://www.w3.org/XML/]. This specification includes by reference Namespaces in XML 1.1, Namespaces in XML 1.0 and Namespaces in XML 1.0 Errata, in their entirety for the purposes of defining Namespaces in XML in the APIs defined herein.

XML Schema This specification supports XML Schema Part 1: Structures [http://www.w3.org/TR/xmlschema-1/], XML Schema Part 1: Structures Errata [http://www.w3.org/2001/05/xmlschema-errata#Errata1], XML Schema Part 2: Datatypes [http://www.w3.org/TR/xmlschema-2/] and XML Schema Part 2: Datatypes Errata [http://www.w3.org/2001/05/xmlschema-errata#Errata2]. XML Schema is a product of the XML Schema Working Group [http://www.w3.org/XML/Schema]. This specification includes by reference XML Schema Part 1: Structures, XML Schema Part 1: Structures Errata, XML Schema Part 2: Datatypes and XML Schema Part 2: Datatypes Errata in their entirety for the purposes of defining XML Schema in the APIs defined herein.

4

Final 1.0.0

Endorsed Specifications

XSL Transformations (XSLT) This specification supports XSL Transformations (XSLT) Version 1.0 [http://www.w3.org/TR/xslt]. XSLT is a product of the W3C Style Activity [http://www.w3.org/Style/Activity]. This specification includes by reference XSL Transformations (XSLT) Version 1.0 in its entirety for the purposes of defining XSLT in the APIs defined herein.

XML Path Language (XPath) This specification supports XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath] and XML Path Language (XPath) Version 1.0 Errata [http://www.w3.org/1999/11/REC-xpath-19991116-errata]. XPath is a product of the W3C XML Activity [http://www.w3.org/XML/Activity] and W3C Style Activity [http://www.w3.org/Style/Activity]. This specification includes by reference XML Path Language (XPath) Version 1.0 and XML Path Language (XPath) Version 1.0 Errata in their entirety for the purposes of defining SAX in the APIs defined herein.

XML Inclusions (XInclude) This specification supports XML Inclusions (XInclude) Version 1.0 [http://www.w3.org/TR/xinclude/]. XInclude is a product of the W3C XML Core Working Group [http://www.w3.org/XML/Core/] as part of the W3C XML Activity [http://www.w3.org/XML/Activity]. This specification includes by reference XML Inclusions (XInclude) Version 1.0. in its entirety for the purposes of defining XInclude in the APIs defined herein.

Document Object Model (DOM) Level 3 This specification supports Document Object Model (DOM) Level 3 Core [http://www.w3.org/TR/DOM-Level-3-Core] and Document Object Model (DOM) Level 3 Load and Save [http://www.w3.org/TR/DOM-Level-3-LS]. DOM Level 3 is a product of the W3C DOM Activity [http://www.w3.org/DOM/]. This specification includes by reference Document Object Model (DOM) Level 3 Core and Document Object Model (DOM) Level 3 Load and Save in their entirety for the purposes of defining SAX in the APIs defined herein. The API packages included by reference are: •

org.w3c.dom



org.w3c.dom.bootstrap



org.w3c.dom.events



org.w3c.dom.ls



org.w3c.dom.ranges



org.w3c.dom.traversal

5

Final 1.0.0

Endorsed Specifications

Simple API for XML (SAX) This specification supports Simple API for XML (SAX) 2.0.2 (sax2r3) [http://sax.sourceforge.net/] and Simple API for XML (SAX) 2.0.2 (sax2r3) Extensions [http://sax.sourceforge.net/?selected=ext]. Simple API for XML (SAX) 2.0.2 (sax2r3) is a product of the SAX Community [http://sax.sourceforge.net/]. This specification includes by reference Simple API for XML (SAX) 2.0.2 (sax2r3) and Simple API for XML (SAX) 2.0.2 (sax2r3) Extensions in their entirety for the purposes of defining Simple API for XML (SAX) 2.0.2 (sax2r3) in the APIs defined herein. The API packages included by reference are: •

org.xml.sax



org.xml.sax.ext



org.xml.sax.helpers

6

Final 1.0.0

Chapter 3. Plugability Layer The endorsed APIs provide broad and useful functionality. However, the use of a SAX or a DOM parser typically requires knowledge of the specific implementation of the parser. Providing the functionality of the endorsed APIs in the Java Platform, while allowing choice of the implementation of the parser, requires a Plugability layer. This section of the specification defines a Plugability mechanism to allow a compliant SAX or DOM parser to be used through the abstract javax.xml.parsers and javax.xml.transform API.

SAX Plugability The SAX Plugability classes allow an application programmer to provide an implementation of the org.xml.sax.DefaultHandler API to a SAXParser38 implementation and parse XML documents. As the parser processes the XML document, it will call methods on the provided DefaultHandler. In order to obtain a SAXParser38 instance, an application programmer first obtains an instance of a SAXParser  Factory47. The SAXParserFactory47 instance is obtained via the static newInstance method of the SAX  ParserFactory47 class. This method uses the following ordered lookup procedure to determine the SAXParserFactory implementation class to load: •

Use the javax.xml.parsers.SAXParserFactory system property.



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.



Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for the classname in the file META-INF/services/javax.xml.parsers.SAXParserFactory in jars available to the runtime.



Platform default SAXParserFactory47 instance.

If the SAXParserFactory47 implementation class cannot be loaded or instantiated at runtime, a FactoryCon  figurationError is thrown. This error message should contain a descriptive explanation of the problem and how the user can resolve it. The instance of SAXParserFactory47 can optionally be configured by the application programmer to provide parsers that are namespace aware, or validating, or both. These settings are made using the setNamespaceAware and setValidating methods of the factory. The application programmer can then obtain a SAXParser38 imple  mentation instance from the factory. If the factory cannot provide a parser configured as set by the application program  mer, then a ParserConfigurationException is thrown.

Examples The following is a simple example of how to parse XML content from a URL:

7

Final 1.0.0

Plugability Layer

SAXParser parser; DefaultHandler handler = new MyApplicationParseHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); try { parser = factory.newSAXParser(); parser.parse("http://myserver/mycontent.xml", handler); } catch (SAXException se) { // handle error } catch (IOException ioe) { // handle error } catch (ParserConfigurationException pce) { // handle error } The following is an example of how to configure a SAX parser to be namespace aware and validating:

SAXParser parser; DefaultHandler handler = new MyApplicationParseHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); try { parser = factory.newSAXParser(); parser.parse("http://myserver/mycontent.xml", handler); } catch (SAXException se) { // handle error } catch (IOException ioe) { // handle error } catch (ParserConfigurationException pce) { // handle error } An example of how one could pass the System property as a command line option is: java -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl user.parserApp

DOM Plugability The DOM plugability classes allow a programmer to parse an XML document and obtain an org.w3c.dom.Docu  ment object from a DocumentBuilder25 implementation which wraps an underlying DOM implementation. In order to obtain a DocumentBuilder25 instance, an application programmer first obtains an instance of a Docu  mentBuilderFactory30. The DocumentBuilderFactory30 instance is obtained via the static newInstance method of the DocumentBuilderFactory30 class. This method uses the following ordered lookup procedure to determine the DocumentBuilderFactory implementation class to load: •

Use the javax.xml.parsers.DocumentBuilderFactory system property



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being

8

Final 1.0.0

Plugability Layer

the system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time. •

Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for the classname in the file META-INF/services/javax.xml.parsers.DocumentBuilderFactory in jars available to the runtime.



Platform default DocumentBuilderFactory30 instance.

If the DocumentBuilderFactory30 implementation class cannot be loaded or instantiated at runtime, a Fact  oryConfigurationError is thrown. This error message should contain a descriptive explanation of the problem and how the user can resolve it. The instance of DocumentBuilderFactory30 can optionally be configured by the application programmer to provide parsers that are namespace aware or validating, or both. These settings are made using the set  NamespaceAware and setValidating methods of the factory. The application programmer can then obtain a DocumentBuilder25 implementation instance from the factory. If the factory cannot provide a parser configured as set by the application programmer, then a ParserConfigurationException is thrown.

Reliance on SAX API The DocumentBuilder reuses several classes from the SAX API. This does not mean that the implementor of the un  derlying DOM implementation must use a SAX parser to parse the XML content, only that the implementation com  municate with the application using these existing and defined APIs.

Examples The following is a simple example of how to parse XML content from a URL:

DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String location = "http://myserver/mycontent.xml"; try { builder = factory.newDocumentBuilder(); Document document = builder.parse(location); } catch (SAXException se) { // handle error } catch (IOException ioe) { // handle error } catch (ParserConfigurationException pce) { // handle error } The following is an example of how to configure a factory to produce parsers to be namespace aware and validating:

DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true);

9

Final 1.0.0

Plugability Layer

String location = "http://myserver/mycontent.xml"; try { builder = factory.newDocumentBuilder(); Document document = builder.parse(location); } catch (SAXException se) { // handle error } catch (IOException ioe) { // handle error } catch (ParserConfigurationException pce) { // handle error } An example of how one could pass the System property as a command line option is: java -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl user.parserApp

XSLT Plugability The XSLT Plugability classes allow an application programmer to obtain a Transformer object that is based on a spe  cific XSLT stylesheet from a TransformerFactory implementation. In order to obtain a Transformer object, a programmer first obtains an instance of the TransformerFactory. The TransformerFactory instance is obtained via the static newIn  stance method of the TransformerFactory class. This method uses the following ordered lookup procedure to determine the TransformerFactory implementation class to load: •

Use the javax.xml.transform.TransformerFactory system property



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.



Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for the classname in the file META-INF/services/javax.xml.transform.TransformerFactory in jars available to the runtime.



Platform default TransformerFactory68 instance.

If the TransformerFactory68 implementation class cannot be loaded or instantiated at runtime, a Transformer  FactoryConfigurationError is thrown. This error message should contain a descriptive explanation of the problem and how the user can resolve it.

Examples The following is a simple example of how to transform XML content:

Transformer transformer; TransformerFactory factory = TransformerFactory.newInstance(); String stylesheet = "file:///home/user/mystylesheet.xsl";

10

Final 1.0.0

Plugability Layer

String sourceId = "file:///home/user/sourcefile.xml"; try { transformer = factory.newTransformer(new StreamSource(stylesheet)); transformer.transform(new StreamSource(sourceId), new StreamResult(System.out)); } catch (Exception e) { // handle error } The following example illustrates the serialization of a DOM node to an XML stream:

TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer serializer = tfactory.newTransformer(); Properties oprops = new Properties(); oprops.put("method", "html"); oprops.put("indent-amount", "2"); serializer.setOutputProperties(oprops); serializer.transform(new DOMSource(doc), new StreamResult(System.out)); Exceptions and Error Reporting The following example illustrates the use of the URIResolver to resolve URIs to DOM nodes, in a transformation whose input is totally DOM based:

TransformerFactory tfactory = TransformerFactory.newInstance(); if (tfactory.getFeature(DOMSource.FEATURE) && tfactory.getFeature(StreamResult.FEATURE)) { DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); // Always, required for XSLT DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); // Set up to resolve URLs that correspond to our inc1.xsl, // to a DOM node. Use an anonymous class for the URI resolver. final Node xslInc1 = docBuilder.parse("xsl/inc1/inc1.xsl"); final Node xslInc2 = docBuilder.parse("xsl/inc2/inc2.xsl"); tfactory.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { // ignore base. return (href.equals("inc1/inc1.xsl")) ? new DOMSource(xslInc1) : (href.equals("inc2/inc2.xs } } );

// The TransformerFactory will call the anonymous URI // resolver set above when it encounters // Templates templates = tfactory.newTemplates(new DOMSource(docBuilder.parse(xslID), xslID)); // Get a transformer from the templates. Transformer transformer = templates.newTransformer(); // Set up to resolve URLs that correspond to our foo2.xml, to

11

Final 1.0.0

Plugability Layer

// a DOM node. Use an anonymous class for the URI resolver. // Be sure to return the same DOM tree every time for the given URI. final Node xmlSubdir1Foo2Node = docBuilder.parse("xml/subdir1/foo2.xml"); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { // ignore base because we’re lazy, or we don’t care. return (href.equals("subdir1/foo2.xml")) ? new DOMSource(xmlSubdir1Foo2Node) : null; } } ); // Now the transformer will call our anonymous URI resolver // when it encounters the document("subdir1/foo2.xml") invocation. transformer.transform(new DOMSource(docBuilder.parse(sourceID), sourceID), }

new StreamResul

The following example performs a transformation using DOM nodes as input for the TransformerFactory, as input for the Transformer, and as the output of the transformation:

TransformerFactory tfactory = TransformerFactory.newInstance(); // Make sure the TransformerFactory supports the DOM feature. if (tfactory.getFeature(DOMSource.FEATURE) && tfactory.getFeature(DOMResult.FEATURE)) { // Use javax.xml.parsers to create our DOMs. DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); // do this always for XSLT DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); // Create the Templates from a DOM. Node xslDOM = docBuilder.parse(xslID); DOMSource dsource = new DOMSource(xslDOM, xslID); Templates templates = tfactory.newTemplates(dsource); // Create the source tree in the form of a DOM. Node sourceNode = docBuilder.parse(sourceID); // Create a DOMResult that the transformation will fill in. DOMResult dresult = new DOMResult(); // And transform from the source DOM tree to a result DOM tree. Transformer transformer = templates.newTransformer(); transformer.transform(new DOMSource(sourceNode, sourceID), dresult); // The root of the result tree may now be obtained from // the DOMResult object. Node out = dresult.getNode(); // Serialize it to System.out for diagnostics. Transformer serializer = tfactory.newTransformer(); serializer.transform(new DOMSource(out), new StreamResult(System.out)); } The following code fragment illustrates the use of the SAXSource and SAXResult objects:

12

Final 1.0.0

Plugability Layer

TransformerFactory tfactory = TransformerFactory.newInstance(); // Does this factory support SAX features? if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(SAXResult.FEATURE)) { // Get a transformer. Transformer transformer = tfactory.newTransformer(new StreamSource(xslID)); // Create a reader for reading. XMLReader reader = XMLReaderFactory.createXMLReader(); transformer.transform(new SAXSource(reader, new InputSource(sourceID)), new SAXResult(new E } The following illustrates the feeding of SAX events from an org.xml.sax.XMLReader to a Transformer:

TransformerFactory tfactory = TransformerFactory.newInstance(); // Does this factory support SAX features? if (tfactory.getFeature(SAXTransformerFactory.FEATURE)) { // If so, we can safely cast. SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory); // A TransformerHandler is a ContentHandler that will listen for // SAX events, and transform them to the result. TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID)); // Set the result handling to be a serialization to System.out. handler.setResult(new StreamResult(System.out)); handler.getTransformer().setParameter("a-param", "hello to you!"); // Create a reader, and set it’s content handler to be the TransformerHandler. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); // It’s a good idea for the parser to send lexical events. // The TransformerHandler is also a LexicalHandler. reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); // Parse the source XML, and send the parse events to the TransformerHandler. reader.parse(sourceID); } The following code fragment illustrates the creation of a Templates object from SAX2 events sent from an XMLReader:

TransformerFactory tfactory = TransformerFactory.newInstance(); // Does this factory support SAX features? if (tfactory.getFeature(SAXTransformerFactory.FEATURE)) { // If so, we can safely cast. SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory); // Have the factory create a special ContentHandler that will // create a Templates object. TemplatesHandler handler = stfactory.newTemplatesHandler(); // If you don’t do this, the TemplatesHandler won’t know how to // resolve relative URLs. handler.setSystemId(xslID);

13

Final 1.0.0

Plugability Layer

// Create a reader, and set it’s content handler to be the TemplatesHandler. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); // Parse the source XML, and send the parse events to the TemplatesHandler. reader.parse(xslID); // Get the Templates reference from the handler. Templates templates = handler.getTemplates(); // Ready to transform. Transformer transformer = templates.newTransformer(); transformer.transform(new StreamSource(sourceID), new StreamResult(System.out)); } The following illustrates several transformations chained together. Each filter points to a parent org.xml.sax.XMLReader ,and the final transformation is caused by invoking org.xml.sax.XMLRead  er#parse on the final reader in the chain:

TransformerFactory tfactory = TransformerFactory.newInstance(); // Does this factory support SAX features? if (tfactory.getFeature(SAXTransformerFactory.FEATURE)) { Templates stylesheet1 = tfactory.newTemplates(new StreamSource(xslID_1)); Transformer transformer1 = stylesheet1.newTransformer(); SAXTransformerFactory stf = (SAXTransformerFactory)tfactory; XMLReader reader = XMLReaderFactory.createXMLReader(); XMLFilter filter1 = stf.newXMLFilter(new StreamSource(xslID_1)); XMLFilter filter2 = stf.newXMLFilter(new StreamSource(xslID_2)); XMLFilter filter3 = stf.newXMLFilter(new StreamSource(xslID_3)); // transformer1 will use a SAX parser as it’s reader. filter1.setParent(reader); // transformer2 will use transformer1 as it’s reader. filter2.setParent(filter1); // transform3 will use transform2 as it’s reader. filter3.setParent(filter2); filter3.setContentHandler(new ExampleContentHandler()); // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler()); // // // // // //

Now, when you call transformer3 to parse, it will set itself as the ContentHandler for transform2, and call transform2.parse, which will set itself as the content handler for transform1, and call transform1.parse, which will set itself as the content listener for the SAX parser, and call parser.parse(new InputSource("xml/foo.xml")).

filter3.parse(new InputSource(sourceID)); } The following code fragment illustrates the use of the stream Source and Result objects:

14

Final 1.0.0

Plugability Layer

// Create a TransformerFactory instance. TransformerFactory tfactory = TransformerFactory.newInstance(); InputStream xslIS = new BufferedInputStream(new FileInputStream(xslID)); StreamSource xslSource = new StreamSource(xslIS); // Note that if we don’t do this, relative URLs cannot be resolved correctly! xslSource.setSystemId(xslID); // Create a transformer for the stylesheet. Transformer transformer = tfactory.newTransformer(xslSource); InputStream xmlIS = new BufferedInputStream(new FileInputStream(sourceID)); StreamSource xmlSource = new StreamSource(xmlIS); // Note that if we don’t do this, relative URLs cannot be resolved correctly! xmlSource.setSystemId(sourceID); // Transform the source XML to System.out. transformer.transform( xmlSource, new StreamResult(System.out)); An example of how one could pass the System property as a command line option is: java -Djavax.xml.transform.TransformerFactory=org.apache.xalan.processor.TransformerFactoryImpl user.parserApp

XPath Plugability The XPath Plugability classes allow an application programmer to obtain an XPath object that is based on a specific object model implementation. In order to obtain an XPath object, a programmer first obtains an instance of the XPathFactory. The XPathFactory instance is obtained via the static newInstance method of the XPathFactory class. This method uses the following ordered lookup procedure to determine the XPathFactory implementation class to load: •

Use the javax.xml.xpath.XPathFactory system property



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.



Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for the classname in the file META-INF/services/javax.xml.xpath.XPathFactory in jars available to the runtime.



Platform default XPathFactory131 instance.

If the XPathFactory131 implementation class cannot be loaded or instantiated at runtime, a XPathFactoryCon  figurationError is thrown. This error message should contain a descriptive explanation of the problem and how the user can resolve it.

15

Final 1.0.0

Plugability Layer

Examples The following example loads a document and evaluates the XPath expression “/widgets/wid  get[@name='a']/@quantity” against it.

// parse the XML as a W3C Document DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); org.w3c.Document document = builder.parse(new File("/widgets.xml")); // evaluate the XPath expression against the Document XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/widgets/widget[@name='a']/@quantity"; Double quantity = (Double) xpath.evaluate(expression, document, XPathConstants.NUMBER); The evaluation of XPath expressions can return their results as one of five types: Node, NodeList, Boolean, Double, and String. The third argument to evaluate selects the result type. To get the quantity attribute as a string, use:

String str_quantity = (String) xpath.evaluate(expression, document, XPathConstants.STRING); This may seem somewhat clumsy, but it is necessary because the he result type is not a property of the expression, it is a property of the context in which it is evaluated.

Validation Plugability The Validation Plugability classes allow an application programmer to obtain a Schema156 Object that is based on a specific schema language implementation. In order to obtain a Schema156 Object, a programmer first obtains an instance of the SchemaFactory157. The SchemaFactory157 instance is obtained via the static newInstance method of the SchemaFactory157 Class. This method uses the following ordered lookup procedure to determine the SchemaFactory157 implementation Class to load: •

If the system property javax.xml.validation.SchemaFactory:schemaLanguage is present (where schemaLanguage is the parameter to newInstance), then its value is read as a Class name. The method will try to create a new instance of this Class by using the ClassLoader, and returns it if it is successfully created.



Read the properties file $java.home/lib/jaxp.properties in the JRE directory. This configuration file is in standard java.util.Properties format. $java.home/lib/jaxp.properties is read only once by the JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in $java.home/lib/jaxp.properties after it has been read for the first time. If the property javax.xml.validation.SchemaFactory:schemaLanguage is present (where schemaLanguage is the parameter to newInstance), then its value is read as a Class name. The method will try to create a new instance of this Class by using the ClassLoader, and returns it if it is successfully created.

16

Final 1.0.0

Plugability Layer



The ClassLoader is asked for service provider provider-configuration files matching javax.xml.valida  tion.SchemaFactory in the resource directory META-INF/services. See the JAR File Specification for file format and parsing rules. Each potential service provider is required to implement the method:

isSchemaLanguageSupported(String schemaLanguage) The first service provider found in ClassLoader order that supports the specified schema language is returned. •

A platform default SchemaFactory157 is located in an implementation specific way. There must be a platform default SchemaFactory157 for W3C®,(World Wide Web Consortium) XML Schema.

If all lookups fail, then an IllegalArgumentException will be thrown.

Tip See Properties.load(java.io.InputStream) for exactly how a property file is parsed. In partic  ular, colons ’:’ need to be escaped in a property file, so make sure schema language URIs are properly escaped. For example:

http\://www.w3.org/2001/XMLSchema=org.acme.XSSchemaFactory

Thread Safety Implementations of the SAXParser38, DocumentBuilder25, Transformer62, Validator172 and Validat  orHandler180 abstract classes are not expected to be thread safe by this specification. This means that application programmers should not expect to be able to use the same instance of a SAXParser38, DocumentBuilder25, Transformer62, Validator172 or ValidatorHandler180 in more than one thread at a time without side effects. If a programmer is creating a multi-threaded application, they should make sure that only one thread has access to any given SAXParser38, DocumentBuilder25, Transformer62, Validator172 or ValidatorHandler180 instance. Configuration of a SAXParserFactory47, DocumentBuilderFactory30 TransformerFactory68 or SchemaFactory157 is also not expected to be thread safe. This means that an application programmer should not allow a SAXParserFactory47, DocumentBuilderFactory30, TransformerFactory68 or SchemaFact  ory157 instance to have its setter methods accessed from more than one thread. It is expected that the newSAXParser50 method of a SAXParserFactory47 implementation, the newDocument  Builder33 method of a DocumentBuilderFactory30 and the newTransformer method of a Transformer  Factory68 will be thread safe without side effects. This means that an application programmer should expect to be able to create parser instances in multiple threads at once from a shared factory without side effects or problems. Note that Schema156 is thread safe.

Properties For Enabling Schema Validation javax.xml.parsers.SAXParserFactory The validating property must have the value true for any of the property strings defined below to take effect. Otherwise, the values of the properties defined below will be ignored. This value can be set by invoking

17

Final 1.0.0

Plugability Layer

setValidating(true) javax.xml.parsers.SAXParser The setProperty method in SAXParser must support the property strings defined below to indicate the schema language and the source of the schema file(s) to the parser: http://java.sun.com/xml/jaxp/properties/schemaLanguage This property defines the schema language to be used for validation. The value of this property must be the URI of the schema language specification. To be compliant with this version of the specification, the implementation must support the W3C XML Schema [http://www.w3.org/2001/XMLSchema] specification. When setValidating is set to true and a schema language is set, then the parser must validate against that schema language only. For example if an application sets the schemaLanguage property to XML Schemas then the parser must try to validate against the XML schema only, even if the document has a DOCTYPE declaration that refers to a DTD. http://java.sun.com/xml/jaxp/properties/schemaSource The XML Schema Recommendation explicitly states that the inclusion of schemaLocation / noNamespaceSchema  Location attributes in an instance document is only a hint; it does not mandate that these attributes must be used to locate schemas. The schemaSource property lets the user set the schema(s) to validate against. If the target namespace of a schema specified using this property matches the target namespace of a schema occurring in schemaLocation attribute, the schema specified by the user using this property will be used and the instance document’s schemaLocation attribute will be effectively ignored. However if the target namespace of any schema specified using this property doesn’t match the target namespace of a schema occurring in the instance document, then the hint specified in the instance document will be used for validation. The acceptable value for this property must be one of the following: •

URI of the schema as a String



InputStream with the contents of the schema



SAX InputSource



File



an array of Objects with the contents being one of the types defined above. An array of Objects can be used only when the schema language has the ability to assemble a schema at runtime. When an array of Objects is passed it is illegal to have two schemas that share the same namespace.

If no target namespace is defined, then only one schema can be referenced by the property and it must work exactly the way xsi:noNamespaceSchemaLocation does. It is illegal to set the schemaSource property if the schemaLanguage property has not been set. In that case, the imple  mentation must throw a SAXNotSupportedException with a detailed message. If the schemaSource property is set using a String, the parser must pass the value of the property to the org.xml.sax.EntityResolver with the publicId set to null. javax.xml.parsers.DocumentBuilderFactory The same property strings as described above for the SAXParser must be supported by DocumentBuilderFact  ory.setAttribute method.

18

Final 1.0.0

Plugability Layer

When setValidating is set to true and a schema language is set then the parser must validate against that schema language only. For example if an application sets the schema language property to XML Schemas the parser must try to validate against the XML schema only, even if the document has a DOCTYPE declaration that refers to a DTD. It is illegal to set the schemaSource property if the schemaLanguage property has not been set. In that case, the imple  mentation must throw an IllegalArgumentException with a detailed message. Note: None of the properties will take effect till the setValidating(true) has been called on the SAXParserFactory or the DocumentBuilderFactory that was used to create the SAXParser or the DocumentBuilder. The table below shows the results of various configuration scenarios. In all cases, we assume that setValidating(true) has been called. Document has schema language schema source schema location Document Valid  Schema file used DOCTYPE? property set to property set? attribute present ated against XML Schemas? in document? no

no

no

no

error as per JAXP N/A 1.1 spec. Must have a DOCTYPE declaration when validation is turned on.

no

no

no

yes

Error. Schema lan  N/A guage must be set.

no

no

yes

yes / no

Error schema lan  N/A guage must be set.

yes / no

yes

no

yes

xml schemas

schema files re  ferred to using the schema location attributes present in the instance document

yes / no

yes

yes

no

xml schemas

schema file re  ferred to in the schemaSource property

yes / no

yes

yes

yes

xml schemas

schema file re  ferred to in the schema source property, if the tar  get namespace matches. The schema file re  ferred to in the schema location attribute is ignored only if the target namespace matches

yes

no

no

yes / no

DTD

DTD referred to in the DOCTYPE

19

Final 1.0.0

Plugability Layer

Document has schema language schema source schema location Document Valid  Schema file used DOCTYPE? property set to property set? attribute present ated against XML Schemas? in document? yes

no

yes

yes / no

Error. Schema N/A source cannot be set without setting the schema lan  guage.

Samples Using the Properties Sax parser sample:

try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); SAXParser sp = spf.newSAXParser(); sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "http://www.example. DefaultHandler dh = new DefaultHandler(); sp.parse("http://www.wombats.com/foo.xml", dh); } catch(SAXException se) { se.printStackTrace(); } DOM parser sample:

try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "http://www.example.com/Report.xsd"); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse("http://www.wombats.com/foo.xml"); } catch(DOMException de) { de.printStackTrace(); }

Recommended Implementation of Properties It is recommended that parser implementations recognize properties defined in the form of a URI, as above. Such im  plementations avoid conflicts in the use of the feature and property strings among parser implementations. That is also the way in which SAX defines feature and property strings.

20

Final 1.0.0

Chapter 4. Conformance Requirements This section describes the conformance requirements for implementations of this specification. Implementations that are accessed via the APIs defined here must implement these constraints, without exception, to provide a predictable environment for application development and deployment. Note that applications may provide non-conformant implementations that are able to support the plugability mechanism defined in the specification, however the system default processor must meet the conformance requirements defined below.

All Implementations of JSR 206 Java™ API for XML Processing (JAXP) 1.3 Must Support the Following Specifications: •

Extensible Markup Language (XML) 1.1 [http://www.w3.org/TR/xml11], Extensible Markup Language (XML) 1.0 (Second Edition) [http://www.w3.org/TR/REC-xml], Extensible Markup Language (XML) 1.0 (Second Edition) Errata [http://www.w3.org/XML/xml-V10-2e-errata]



Namespaces in XML 1.1 [http://www.w3.org/TR/xml-names11/], Namespaces in [spec.namespaces-1.0.link;], Namespaces in XML 1.0 Errata [spec.namespaces-1.0-errata.link;]



XML Schema Part 1: Structures [http://www.w3.org/TR/xmlschema-1/], XML Schema Part 1: Structures Errata [http://www.w3.org/2001/05/xmlschema-errata#Errata1], XML Schema Part 2: Datatypes [http://www.w3.org/TR/xmlschema-2/], XML Schema Part 2: Datatypes Errata [http://www.w3.org/2001/05/xmlschema-errata#Errata2]



XSL Transformations (XSLT) Version 1.0 [http://www.w3.org/TR/xslt], XSL Transformations (XSLT) Version 1.0 Errata [http://www.w3.org/1999/11/REC-xslt-19991116-errata]



XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath], XML Path Language (XPath) Version 1.0 Errata [http://www.w3.org/1999/11/REC-xpath-19991116-errata]



XML Inclusions (XInclude) Version 1.0 [http://www.w3.org/TR/xinclude/]



Document Object Model (DOM) Level 3 Core [http://www.w3.org/TR/DOM-Level-3-Core], Document Object Model (DOM) Level 3 Load and Save



Simple API for XML (SAX) 2.0.2 (sax2r3) [http://sax.sourceforge.net/], http://sax.sourceforge.net/?selected=ext

21

Final 1.0.0

XML

1.0

Chapter 5. XML Inclusions (XInclude) What is XML Inclusions (XInclude) JSR 206 Java™ API for XML Processing (JAXP) 1.3 supports XInclude as defined in XML Inclusions (XInclude) Version 1.0 [http://www.w3.org/TR/xinclude/]. XInclude specifies a processing model and syntax for general purpose inclusion. Inclusion is accom  plished by merging a number of XML information sets into a single composite Infoset. Specification of the XML documents (infosets) to be merged and control over the merging process is expressed in XML-friendly syntax (elements, attributes, URI references). — XML Inclusions (XInclude) Version 1.0, Abstract [http://www.w3.org/TR/xinclude/#abstract]

Implementation Required by JSR 206 Java™ API for XML Processing (JAXP) 1.3 JSR 206 Java™ API for XML Processing (JAXP) 1.3 implements XML Inclusions (XInclude) Version 1.0 with the following limitations •

at the time this specification was developed, there was no standard fragment identifier syntax for “application/xml” resources



supports XPointers using the XPointer Framework and XPointer element() scheme



no other XPointer schemes or addressing mechanisms are supported and it is an error to use an other XPointer scheme or addressing mechanism, the error is signaled by throwing a java.lang.Exception for DOM processing and an org.xml.sax.SAXParseException for SAX processing

XInclude processing defaults to false. See Javadoc for javax.xml.parsers.DocumentBuilderFactory javax.xml.parsers.SAXParserFactory for methods to enable/disable/query the state of XInclude processing.

22

Final 1.0.0

and

Chapter 6. JSR 206 Java™ API for XML Processing (JAXP) 1.3 Specification and Implementation Version Information JSR 206 Java™ API for XML Processing (JAXP) 1.3 Specification Version Information JSR 206 Java™ API for XML Processing (JAXP) 1.3 specification version information is made available via java.lang.Package methods •

public String getSpecificationTitle(); Return the title of the specification that this package implements. null is returned if it is not known.



public String getSpecificationVersion(); Returns the version number of the specification that this package implements. This version string must be a sequence of positive decimal integers separated by "."'s and may have leading zeros. When version strings are compared the most significant numbers are compared. null is returned if it is not known.



public String getSpecificationVendor(); Returns the name of the organization, vendor, or company that owns and maintains the specification of the classes that implement this package. null is returned if it is not known.

This version information is retrieved and made available by the ClassLoader instance that loaded the class(es). Typically, it is stored in the manifest that is distributed with the classes. Implementations are required to provide this information with the following values:

Table 6.1. JSR 206 Java™ API for XML Processing (JAXP) 1.3 Specification Version Information Specification Title

JSR 206 Java™ API for XML Processing (JAXP) 1.3

Specification Vendor

Sun Microsystems, Inc.

Specification Version

1.3

Sample META-INF/MANIFEST.MF entries to provide this information would be: Specification-Title : JSR 206 Java™ API for XML Processing (JAXP) 1.3 Specification-Vendor : Sun Microsystems, Inc. Specification-Version : 1.3 See the JAR File Specification, ${JAVA_HOME}/docs/guide/jar/jar.html, for detailed format information.

23

Final 1.0.0

JSR 206 Java API for XML Processing (JAXP) 1.3 Specification and Implementa  tion Version Information

JSR 206 Java™ API for XML Processing (JAXP) 1.3 Implementation Version Information JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation version information is made available via java.lang.Package methods •

public String getImplementationTitle(); Return the title of this package. null is returned if it is not known.



public String getImplementationVersion(); Returns the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime. It may be compared for equality with other package version strings used for this implementation by this vendor for this package. null is returned if it is not known.



public String getImplementationVendor(); Returns the name of the organization, vendor or company that provided this implementation.

This version information is retrieved and made available by the ClassLoader instance that loaded the class(es). Typically, it is stored in the manifest that is distributed with the classes. Implementations are required to provide this information with reasonable values: Implementation Title Implementation Vendor Implementation Version Sample META-INF/MANIFEST.MF entries to provide this information would be: Implementation-Title : My Implementation Title Implementation-Vendor : My Implementation Vendor Implementation-Version : My Implementation Version See the JAR File Specification, ${JAVA_HOME}/docs/guide/jar/jar.html, for detailed format information.

24

Final 1.0.0

Chapter 7. Package 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)

Class DocumentBuilder Defines the API to obtain DOM Document instances from an XML document. Using this class, an application program  mer can obtain a org.w3c.dom.Document from XML. An instance of this class can be obtained from the javax.xml.parsers.DocumentBuilderFactory.newDocumentBuilder [ Method newDocumentBuilder()] method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources. Note that this class reuses several classes from the SAX API. This does not require that the implementor of the under  lying DOM implementation use a SAX parser to parse XML document into a Document. It merely requires that the implementation communicate with the application using these existing APIs.

Synopsis public DocumentBuilder { protected DocumentBuilder(); public void reset(); public Document parse(java.io.InputStream is)     throws org.xml.sax.SAXException, java.io.IOException; public Document parse(java.io.InputStream is,                         java.lang.String systemId)     throws org.xml.sax.SAXException, java.io.IOException; public Document parse(java.lang.String uri)     throws org.xml.sax.SAXException, java.io.IOException; public Document parse(java.io.File f)     throws org.xml.sax.SAXException, java.io.IOException; public Document abstract parse(org.xml.sax.InputSource is)     throws org.xml.sax.SAXException, java.io.IOException; public boolean abstract isNamespaceAware(); public boolean abstract isValidating(); public void abstract setEntityResolver(org.xml.sax.EntityResolver er); public void abstract setErrorHandler(org.xml.sax.ErrorHandler eh); public Document abstract newDocument();

25

Final 1.0.0

Package javax.xml.parsers

public DOMImplementation abstract getDOMImplementation(); public Schema getSchema(); public boolean isXIncludeAware(); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.25.14.1.2.1 $, $Date: 2004/06/28 18:23:44 $

Inheritance Path java.lang.Object | javax.xml.parsers.DocumentBuilder

Members Constructor DocumentBuilder() protected DocumentBuilder(); Protected constructor

Method getDOMImplementation() public DOMImplementation abstract getDOMImplementation(); Obtain an instance of a org.w3c.dom.DOMImplementation object.

Method getSchema() public Schema getSchema();

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Get a reference to the the javax.xml.validation.Schema being used by the XML processor. If no schema is being used, null is returned.

Method isNamespaceAware() public boolean abstract isNamespaceAware(); Indicates whether or not this parser is configured to understand namespaces.

26

Final 1.0.0

Package javax.xml.parsers

Method isValidating() public boolean abstract isValidating(); Indicates whether or not this parser is configured to validate XML documents.

Method isXIncludeAware() public boolean isXIncludeAware();

Exceptions UnsupportedOperationEx  ception

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

Since

1.5

See Also

javax.xml.parsers.DocumentBuilderFactory.setXIncludeAware Aware(boolean)]

[Method

setXInclude 

Get the XInclude processing mode for this parser.

Method newDocument() public Document abstract newDocument(); Obtain a new instance of a DOM org.w3c.dom.Document object to build a DOM tree with.

Method parse(File) public Document parse(java.io.File f)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters f

The file containing the XML to parse.

returns

A new DOM Document object.

Exceptions IOException

If any IO errors occur.

SAXException

If any parse errors occur.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given file as an XML document and return a new DOM org.w3c.dom.Document object. An IllegalArgumentException is thrown if the File is null null.

Method parse(InputSource) public Document abstract parse(org.xml.sax.InputSource is)     throws org.xml.sax.SAXException, java.io.IOException;

27

Final 1.0.0

Package javax.xml.parsers

Parameters is

InputSource containing the content to be parsed.

returns

A new DOM Document object.

Exceptions IOException

If any IO errors occur.

SAXException

If any parse errors occur.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given input source as an XML document and return a new DOM org.w3c.dom.Document object. An IllegalArgumentException is thrown if the InputSource is null null.

Method parse(InputStream) public Document parse(java.io.InputStream is)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

InputStream containing the content to be parsed.

returns

Document result of parsing the InputStream

Exceptions IOException

If any IO errors occur.

SAXException

If any parse errors occur.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given InputStream as an XML document and return a new DOM org.w3c.dom.Document object. An IllegalArgumentException is thrown if the InputStream is null.

Method parse(InputStream, String) public Document parse(java.io.InputStream is,                         java.lang.String systemId)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

InputStream containing the content to be parsed.

systemId

Provide a base for resolving relative URIs.

returns

A new DOM Document object.

28

Final 1.0.0

Package javax.xml.parsers

Exceptions IOException

If any IO errors occur.

SAXException

If any parse errors occur.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given InputStream as an XML document and return a new DOM org.w3c.dom.Document object. An IllegalArgumentException is thrown if the InputStream is null.

Method parse(String) public Document parse(java.lang.String uri)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters uri

The location of the content to be parsed.

returns

A new DOM Document object.

Exceptions IOException

If any IO errors occur.

SAXException

If any parse errors occur.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given URI as an XML document and return a new DOM org.w3c.dom.Document object. An IllegalArgumentException is thrown if the URI is null null.

Method reset() public void reset(); Since

1.5

Reset this DocumentBuilder25 to its original configuration. DocumentBuilder25 is reset to the same state as when it was created with javax.xml.parsers.DocumentBuilderFact  ory.newDocumentBuilder [ Method newDocumentBuilder()]. reset() is designed to allow the reuse of existing DocumentBuilder25s thus saving resources associated with the creation of new DocumentBuilder25s. The reset DocumentBuilder25 is not guaranteed to have the same org.xml.sax.EntityResolver or org.xml.sax.Er  rorHandler Objects, e.g. java.lang.Object.equals. It is guaranteed to have a functionally equal EntityResolver and ErrorHandler.

Method setEntityResolver(EntityResolver) public void abstract setEntityResolver(org.xml.sax.EntityResolver er);

29

Final 1.0.0

Package javax.xml.parsers

Parameters er

The EntityResolver to be used to resolve entities present in the XML document to be parsed.

Specify the org.xml.sax.EntityResolver to be used to resolve entities present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it's own default implementation and behavior.

Method setErrorHandler(ErrorHandler) public void abstract setErrorHandler(org.xml.sax.ErrorHandler eh);

Parameters eh

The ErrorHandler to be used by the parser.

Specify the org.xml.sax.ErrorHandler to be used by the parser. Setting this to null will result in the underlying im  plementation using it's own default implementation and behavior.

Class DocumentBuilderFactory Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.

Synopsis public DocumentBuilderFactory { protected DocumentBuilderFactory(); static DocumentBuilderFactory newInstance(); public DocumentBuilder abstract newDocumentBuilder()     throws ParserConfigurationException; public void setNamespaceAware(boolean awareness); public void setValidating(boolean validating); public void setIgnoringElementContentWhitespace(boolean whitespace); public void setExpandEntityReferences(boolean expandEntityRef); public void setIgnoringComments(boolean ignoreComments); public void setCoalescing(boolean coalescing); public boolean isNamespaceAware(); public boolean isValidating(); public boolean isIgnoringElementContentWhitespace(); public boolean isExpandEntityReferences(); public boolean isIgnoringComments();

30

Final 1.0.0

Package javax.xml.parsers

public boolean isCoalescing(); public void abstract setAttribute(java.lang.String name,                                     java.lang.Object value)     throws java.lang.IllegalArgumentException; public Object abstract getAttribute(java.lang.String name)     throws java.lang.IllegalArgumentException; public void abstract setFeature(java.lang.String name,                                   boolean value)     throws ParserConfigurationException; public boolean abstract getFeature(java.lang.String name)     throws ParserConfigurationException; public Schema getSchema(); public void setSchema(javax.xml.validation.Schema schema); public void setXIncludeAware(boolean state); public boolean isXIncludeAware(); } Author

Jeff Suttor [[email protected]]

Version

$Revision: 1.39.16.1 $, $Date: 2004/07/17 00:22:03 $

Inheritance Path java.lang.Object | javax.xml.parsers.DocumentBuilderFactory

Members Method getAttribute(String) public Object abstract getAttribute(java.lang.String name)     throws java.lang.IllegalArgumentException;

Parameters name

The name of the attribute.

returns

value The value of the attribute.

Exceptions IllegalArgumentException

thrown if the underlying implementation doesn't recognize the attribute.

Allows the user to retrieve specific attributes on the underlying implementation.

31

Final 1.0.0

Package javax.xml.parsers

Method getFeature(String) public boolean abstract getFeature(java.lang.String name)     throws ParserConfigurationException;

Parameters name

Feature name.

returns

State of the named feature.

Exceptions ParserConfigurationExcep  tion

if this DocumentBuilderFactory30 or the DocumentBuilder25s it creates cannot support this feature.

Get the state of the named feature. Feature names are fully qualified java.net.URIs. Implementations may define their own features. An javax.xml.pars  ers.ParserConfigurationException [ Exception ParserConfigurationException] is thrown if this DocumentBuilder  Factory30 or the DocumentBuilder25s it creates cannot support the feature. It is possible for an Document  BuilderFactory30 to expose a feature value but be unable to change its state.

Method getSchema() public Schema getSchema();

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Gets the javax.xml.validation.Schema object specified through the javax.xml.parsers.DocumentBuilderFactory.setSchema [ Method setSchema(javax.xml.validation.Schema)] method.

Method isCoalescing() public boolean isCoalescing(); Indicates whether or not the factory is configured to produce parsers which converts CDATA nodes to Text nodes and appends it to the adjacent (if any) Text node.

Method isExpandEntityReferences() public boolean isExpandEntityReferences(); Indicates whether or not the factory is configured to produce parsers which expand entity reference nodes.

Method isIgnoringComments() public boolean isIgnoringComments();

32

Final 1.0.0

Package javax.xml.parsers

Indicates whether or not the factory is configured to produce parsers which ignores comments.

Method isIgnoringElementContentWhitespace() public boolean isIgnoringElementContentWhitespace(); Indicates whether or not the factory is configured to produce parsers which ignore ignorable whitespace in element content.

Method isNamespaceAware() public boolean isNamespaceAware(); Indicates whether or not the factory is configured to produce parsers which are namespace aware.

Method isValidating() public boolean isValidating(); Indicates whether or not the factory is configured to produce parsers which validate the XML content during parse.

Method isXIncludeAware() public boolean isXIncludeAware();

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Get state of XInclude processing.

Method newDocumentBuilder() public DocumentBuilder abstract newDocumentBuilder()     throws ParserConfigurationException;

Exceptions ParserConfigurationExcep  tion

if a DocumentBuilder cannot be created which satisfies the configuration requested.

Creates a new instance of a javax.xml.parsers.DocumentBuilder [ Class DocumentBuilder] using the currently configured parameters.

Method newInstance() static DocumentBuilderFactory newInstance();

33

Final 1.0.0

Package javax.xml.parsers

Exceptions FactoryConfigurationErr  or

if the implementation is not available or cannot be instantiated.

Obtain a new instance of a DocumentBuilderFactory30. This static method creates a new factory instance. This method uses the following ordered lookup procedure to determine the DocumentBuilderFactory30 implement  ation class to load: •

Use the javax.xml.parsers.DocumentBuilderFactory system property.



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JAXP implementation and it's values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.



Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.parsers.DocumentBuild  erFactory in jars available to the runtime.



Platform default DocumentBuilderFactory30 instance.

Once an application has obtained a reference to a DocumentBuilderFactory30 it can use the factory to configure and obtain parser instances.

Tip for Trouble-shooting Setting the jaxp.debug system property will cause this method to print a lot of debug messages to

System.err about what it is doing and where it is looking at. If you have problems loading javax.xml.parsers.DocumentBuilder [ Class DocumentBuilder]s, try:

java -Djaxp.debug=1 YourProgram ....

Method setAttribute(String, Object) public void abstract setAttribute(java.lang.String name,                                     java.lang.Object value)     throws java.lang.IllegalArgumentException;

Parameters name

The name of the attribute.

value

The value of the attribute.

34

Final 1.0.0

Package javax.xml.parsers

Exceptions IllegalArgumentException

thrown if the underlying implementation doesn't recognize the attribute.

Allows the user to set specific attributes on the underlying implementation.

Method setCoalescing(boolean) public void setCoalescing(boolean coalescing);

Parameters coalescing

true if the parser produced will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node; false otherwise.

Specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node. By default the value of this is set to false

Method setExpandEntityReferences(boolean) public void setExpandEntityReferences(boolean expandEntityRef);

Parameters expandEntityRef

true if the parser produced will expand entity reference nodes; false otherwise.

Specifies that the parser produced by this code will expand entity reference nodes. By default the value of this is set to true

Method setFeature(String, boolean) public void abstract setFeature(java.lang.String name,                                   boolean value)     throws ParserConfigurationException;

Parameters name

Feature name.

value

Is feature state true or false.

Exceptions ParserConfigurationExcep  tion

if this DocumentBuilderFactory30 or the DocumentBuilder25s it creates cannot support this feature.

NullPointerException

If the name parameter is null.

Set a feature for this DocumentBuilderFactory30 and DocumentBuilder25s created by this factory. Feature names are fully qualified java.net.URIs. Implementations may define their own features. An javax.xml.pars  ers.ParserConfigurationException [ Exception ParserConfigurationException] is thrown if this DocumentBuilder  Factory30 or the DocumentBuilder25s it creates cannot support the feature. It is possible for an Document  BuilderFactory30 to expose a feature value but be unable to change its state.

35

Final 1.0.0

Package javax.xml.parsers

All implementations are required to support the javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING feature. When the feature is: •

true: the implementation will limit XML processing to conform to implementation limits. Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources. If XML processing is limited for security reasons, it will be reported via a call to the registered org.xml.sax.ErrorHandler.fatalError. See javax.xml.parsers.DocumentBuilder.setErrorHandler [ Method setErrorHandler(org.xml.sax.ErrorHandler)].



false: the implementation will processing XML according to the XML specifications without regard to possible implementation limits.

Method setIgnoringComments(boolean) public void setIgnoringComments(boolean ignoreComments);

Parameters ignoreComments

boolean value to ignore comments during processing

Specifies that the parser produced by this code will ignore comments. By default the value of this is set to false .

Method setIgnoringElementContentWhitespace(boolean) public void setIgnoringElementContentWhitespace(boolean whitespace);

Parameters whitespace

true if the parser created must eliminate whitespace in the element content when parsing XML documents; false otherwise.

Specifies that the parsers created by this factory must eliminate whitespace in element content (sometimes known loosely as 'ignorable whitespace') when parsing XML documents (see XML Rec 2.10). Note that only whitespace which is directly contained within element content that has an element only content model (see XML Rec 3.2.1) will be eliminated. Due to reliance on the content model this setting requires the parser to be in validating mode. By default the value of this is set to false.

Method setNamespaceAware(boolean) public void setNamespaceAware(boolean awareness);

Parameters awareness

true if the parser produced will provide support for XML namespaces; false otherwise.

Specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false

Method setSchema(Schema) public void setSchema(javax.xml.validation.Schema schema);

Parameters schema

Schema156 to use or null to remove a schema.

36

Final 1.0.0

Package javax.xml.parsers

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Set the javax.xml.validation.Schema to be used by parsers created from this factory. When a javax.xml.validation.Schema is non-null, a parser will use a validator created from it to validate documents before it passes information down to the application. When errors are found by the validator, the parser is responsible to report them to the user-specified org.w3c.dom.DOMErrorHandler (or if the error handler is not set, ignore them or throw them), just like any other errors found by the parser itself. In other words, if the user-specified org.w3c.dom.DOMErrorHandler is set, it must receive those errors, and if not, they must be treated according to the implementation specific default error handling rules. A validator may modify the outcome of a parse (for example by adding default values that were missing in documents), and a parser is responsible to make sure that the application will receive modified DOM trees. Initialy, null is set as the javax.xml.validation.Schema. This processing will take effect even if the javax.xml.parsers.DocumentBuilderFactory.isValidating [ Method isValid  ating()] method returns

false . It is an error to use the http://java.sun.com/xml/jaxp/properties/schemaSource property and/or the http://java.sun.com/xml/jaxp/properties/schemaLanguage property in conjunction with a javax.xml.validation.Schema object. Such configuration will cause a javax.xml.parsers.ParserConfigurationException [ Exception ParserConfigurationException] exception when the javax.xml.parsers.DocumentBuilderFactory.newDoc  umentBuilder [ Method newDocumentBuilder()] is invoked.

Note for implmentors A parser must be able to work with any javax.xml.validation.Schema implementation. However, parsers and schemas are allowed to use implementation-specific custom mechanisms as long as they yield the result described in the spe  cification.

Method setValidating(boolean) public void setValidating(boolean validating);

Parameters validating

true if the parser produced will validate documents as they are parsed; false otherwise.

Specifies that the parser produced by this code will validate documents as they are parsed. By default the value of this is set to false.

37

Final 1.0.0

Package javax.xml.parsers

Note that "the validation" here means a validating parser [http://www.w3.org/TR/REC-xml#proc-types] as defined in the XML recommendation. In other words, it essentially just controls the DTD validation. (except the legacy two properties defined in JAXP 1.2. See here [#validationCompatibility] for more details.) To use modern schema languages such as W3C XML Schema or RELAX NG instead of DTD, you can configure your parser to be a non-validating parser by leaving the javax.xml.parsers.DocumentBuilderFactory.setValidating [ Method setValidating(boolean)] method

false , then use the javax.xml.parsers.DocumentBuilderFactory.setSchema [ Method setSchema(javax.xml.validation.Schema)] method to associate a schema to a parser.

Method setXIncludeAware(boolean) public void setXIncludeAware(boolean state);

Parameters state

Set XInclude processing to true or false

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Set state of XInclude processing. If XInclude markup is found in the document instance, should it be processed as specified in XML Inclusions (XInclude) Version 1.0 [http://www.w3.org/TR/xinclude/]. XInclude processing defaults to false.

Class SAXParser Defines the API that wraps an org.xml.sax.XMLReader implementation class. In JAXP 1.0, this class wrapped the org.xml.sax.Parser interface, however this interface was replaced by the org.xml.sax.XMLReader. For ease of transition, this class continues to support the same name and interface as well as supporting new methods. An instance of this class can be obtained from the javax.xml.parsers.SAXParserFactory.newSAXParser [ Method newSAXParser()] method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources. This static method creates a new factory instance based on a system property setting or uses the platform default if no property has been defined. The system property that controls which Factory implementation to create is named "javax.xml.parsers.SAX  ParserFactory". This property names a class that is a concrete subclass of this abstract class. If no property is defined, a platform default will be used. As the content is parsed by the underlying parser, methods of the given org.xml.sax.HandlerBase or the org.xml.sax.helpers.DefaultHandler are called.

38

Final 1.0.0

Package javax.xml.parsers

Implementors of this class which wrap an underlaying implementation can consider using the org.xml.sax.help  ers.ParserAdapter class to initially adapt their SAX1 impelemntation to work under this revised class.

Synopsis public SAXParser { protected SAXParser(); public void reset(); public void parse(java.io.InputStream is,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is,                     org.xml.sax.HandlerBase hb,                     java.lang.String systemId)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.InputStream is,                     org.xml.sax.helpers.DefaultHandler dh,                     java.lang.String systemId)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.lang.String uri,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.lang.String uri,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.File f,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(java.io.File f,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(org.xml.sax.InputSource is,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException; public void parse(org.xml.sax.InputSource is,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException; public Parser abstract getParser()     throws org.xml.sax.SAXException;

39

Final 1.0.0

Package javax.xml.parsers

public XMLReader abstract getXMLReader()     throws org.xml.sax.SAXException; public boolean abstract isNamespaceAware(); public boolean abstract isValidating(); public void abstract setProperty(java.lang.String name,                                    java.lang.Object value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public Object abstract getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public Schema getSchema(); public boolean isXIncludeAware(); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.28.12.1.2.1 $, $Date: 2004/05/02 04:30:56 $

Inheritance Path java.lang.Object | javax.xml.parsers.SAXParser

Members Constructor SAXParser() protected SAXParser(); Protected constructor to prevent instaniation. Use javax.xml.parsers.SAXParserFactory.newSAXParser [ Method newSAXParser()].

Method getParser() public Parser abstract getParser()     throws org.xml.sax.SAXException;

Exceptions SAXException

If any SAX errors occur during processing.

Returns the SAX parser that is encapsultated by the implementation of this class.

Method getProperty(String) public Object abstract getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

40

Final 1.0.0

Package javax.xml.parsers

Parameters name

The name of the property to be retrieved.

returns

Value of the requested property.

Exceptions SAXNotRecognizedEx  ception

When the underlying XMLReader does not recognize the property name.

SAXNotSupportedExcep  tion

When the underlying XMLReader recognizes the property name but doesn't support the property.

See Also

org.xml.sax.XMLReader.getProperty

Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.

Method getSchema() public Schema getSchema();

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Get a reference to the the javax.xml.validation.Schema being used by the XML processor. If no schema is being used, null is returned.

Method getXMLReader() public XMLReader abstract getXMLReader()     throws org.xml.sax.SAXException;

Exceptions SAXException

If any SAX errors occur during processing.

Returns the org.xml.sax.XMLReader that is encapsulated by the implementation of this class.

Method isNamespaceAware() public boolean abstract isNamespaceAware(); Indicates whether or not this parser is configured to understand namespaces.

Method isValidating() public boolean abstract isValidating(); Indicates whether or not this parser is configured to validate XML documents.

41

Final 1.0.0

Package javax.xml.parsers

Method isXIncludeAware() public boolean isXIncludeAware();

Exceptions UnsupportedOperationEx  ception

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

Since

1.5

See Also

javax.xml.parsers.SAXParserFactory.setXIncludeAware [Method setXIncludeAware(boolean)]

Get the XInclude processing mode for this parser.

Method parse(File, DefaultHandler) public void parse(java.io.File f,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters f

The file containing the XML to parse

dh

The SAX DefaultHandler to use.

Exceptions IllegalArgumentException

If the File object is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

Parse the content of the file specified as XML using the specified org.xml.sax.helpers.DefaultHandler.

Method parse(File, HandlerBase) public void parse(java.io.File f,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters f

The file containing the XML to parse

hb

The SAX HandlerBase to use.

Exceptions IllegalArgumentException

If the File object is null.

42

Final 1.0.0

Package javax.xml.parsers

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

Parse the content of the file specified as XML using the specified org.xml.sax.HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Method parse(InputSource, DefaultHandler) public void parse(org.xml.sax.InputSource is,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

The InputSource containing the content to be parsed.

dh

The SAX DefaultHandler to use.

Exceptions IllegalArgumentException

If the InputSource object is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler.

Method parse(InputSource, HandlerBase) public void parse(org.xml.sax.InputSource is,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

The InputSource containing the content to be parsed.

hb

The SAX HandlerBase to use.

Exceptions IllegalArgumentException

If the InputSource object is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

43

Final 1.0.0

Package javax.xml.parsers

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Method parse(InputStream, DefaultHandler) public void parse(java.io.InputStream is,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

InputStream containing the content to be parsed.

dh

The SAX DefaultHandler to use.

Exceptions IllegalArgumentException

If the given InputStream is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given java.io.InputStream instance as XML using the specified org.xml.sax.helpers.DefaultHand  ler.

Method parse(InputStream, DefaultHandler, String) public void parse(java.io.InputStream is,                     org.xml.sax.helpers.DefaultHandler dh,                     java.lang.String systemId)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

InputStream containing the content to be parsed.

dh

The SAX DefaultHandler to use.

systemId

The systemId which is needed for resolving relative URIs.

Exceptions IllegalArgumentException

If the given InputStream is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

version of this method instead.

Parse the content of the given java.io.InputStream instance as XML using the specified org.xml.sax.helpers.DefaultHand  ler.

44

Final 1.0.0

Package javax.xml.parsers

Method parse(InputStream, HandlerBase) public void parse(java.io.InputStream is,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

InputStream containing the content to be parsed.

hb

The SAX HandlerBase to use.

Exceptions IllegalArgumentException

If the given InputStream is null.

SAXException

If parse produces a SAX error.

IOException

If an IO error occurs interacting with the InputStream.

See Also

org.xml.sax.DocumentHandler

Parse the content of the given java.io.InputStream instance as XML using the specified org.xml.sax.HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0.

Method parse(InputStream, HandlerBase, String) public void parse(java.io.InputStream is,                     org.xml.sax.HandlerBase hb,                     java.lang.String systemId)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters is

InputStream containing the content to be parsed.

hb

The SAX HandlerBase to use.

systemId

The systemId which is needed for resolving relative URIs.

Exceptions IllegalArgumentException

If the given InputStream is null.

IOException

If any IO error occurs interacting with the InputStream.

SAXException

If any SAX errors occur during processing.

See Also

version of this method instead.

Parse the content of the given java.io.InputStream instance as XML using the specified org.xml.sax.HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0.

45

Final 1.0.0

Package javax.xml.parsers

Method parse(String, DefaultHandler) public void parse(java.lang.String uri,                     org.xml.sax.helpers.DefaultHandler dh)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters uri

The location of the content to be parsed.

dh

The SAX DefaultHandler to use.

Exceptions IllegalArgumentException

If the uri is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified org.xml.sax.helpers.DefaultHandler.

Method parse(String, HandlerBase) public void parse(java.lang.String uri,                     org.xml.sax.HandlerBase hb)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters uri

The location of the content to be parsed.

hb

The SAX HandlerBase to use.

Exceptions IllegalArgumentException

If the uri is null.

IOException

If any IO errors occur.

SAXException

If any SAX errors occur during processing.

See Also

org.xml.sax.DocumentHandler

Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified org.xml.sax.HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Method reset() public void reset();

46

Final 1.0.0

Package javax.xml.parsers

Since

1.5

Reset this SAXParser38 to its original configuration. SAXParser38 is reset to the same state as when it was created with javax.xml.parsers.SAXParserFactory.newSAX  Parser [ Method newSAXParser()]. reset() is designed to allow the reuse of existing SAXParser38s thus saving resources associated with the creation of new SAXParser38s. The reset SAXParser38 is not guaranteed to have the same javax.xml.validation.Schema Object, e.g. java.lang.Object.equals. It is guaranteed to have a functionally equal Schema156.

Method setProperty(String, Object) public void abstract setProperty(java.lang.String name,                                    java.lang.Object value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The name of the property to be set.

value

The value of the property to be set.

Exceptions SAXNotRecognizedEx  ception

When the underlying XMLReader does not recognize the property name.

SAXNotSupportedExcep  tion

When the underlying XMLReader recognizes the property name but doesn't support the property.

See Also

org.xml.sax.XMLReader.setProperty

Sets the particular property in the underlying implementation of org.xml.sax.XMLReader. A list of the core features and properties can be found at http://sax.sourceforge.net/?selected=get-set [http://sax.sourceforge.net/?selected=get-set].

Class SAXParserFactory Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.

Synopsis public SAXParserFactory { protected SAXParserFactory(); static SAXParserFactory newInstance(); public SAXParser abstract newSAXParser()     throws ParserConfigurationException, org.xml.sax.SAXException; public void setNamespaceAware(boolean awareness);

47

Final 1.0.0

Package javax.xml.parsers

public void setValidating(boolean validating); public boolean isNamespaceAware(); public boolean isValidating();

public void abstract setFeature(java.lang.String name,                                   boolean value)     throws ParserConfigurationException, org.xml.sax.SAXNotRecognizedException, org.xml.sax

public boolean abstract getFeature(java.lang.String name)     throws ParserConfigurationException, org.xml.sax.SAXNotRecognizedException, org.xml.sax public Schema getSchema(); public void setSchema(javax.xml.validation.Schema schema); public void setXIncludeAware(boolean state); public boolean isXIncludeAware(); } Author

Jeff Suttor [[email protected]]

Version

$Revision: 1.39 $, $Date: 2004/04/20 00:22:02 $

Inheritance Path java.lang.Object | javax.xml.parsers.SAXParserFactory

Members Constructor SAXParserFactory() protected SAXParserFactory(); Protected constructor to force use of javax.xml.parsers.SAXParserFactory.newInstance [ Method newInstance()].

Method getFeature(String)

public boolean abstract getFeature(java.lang.String name)     throws ParserConfigurationException, org.xml.sax.SAXNotRecognizedException, org.xml.sax

Parameters name

The name of the property to be retrieved.

returns

Value of the requested property.

48

Final 1.0.0

Package javax.xml.parsers

Exceptions ParserConfigurationExcep  tion

if a parser cannot be created which satisfies the requested configuration.

SAXNotRecognizedEx  ception

When the underlying XMLReader does not recognize the property name.

SAXNotSupportedExcep  tion

When the underlying XMLReader recognizes the property name but doesn't support the property.

See Also

org.xml.sax.XMLReader.getProperty

Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.

Method getSchema() public Schema getSchema();

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Gets the javax.xml.validation.Schema object specified through the javax.xml.parsers.SAXParserFactory.setSchema [ Method setSchema(javax.xml.validation.Schema)] method.

Method isNamespaceAware() public boolean isNamespaceAware(); Indicates whether or not the factory is configured to produce parsers which are namespace aware.

Method isValidating() public boolean isValidating(); Indicates whether or not the factory is configured to produce parsers which validate the XML content during parse.

Method isXIncludeAware() public boolean isXIncludeAware();

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Get state of XInclude processing.

49

Final 1.0.0

Package javax.xml.parsers

Method newInstance() static SAXParserFactory newInstance();

Exceptions FactoryConfigurationErr  or

if the implementation is not available or cannot be instantiated.

Obtain a new instance of a SAXParserFactory47. This static method creates a new factory instance This method uses the following ordered lookup procedure to determine the SAXParserFactory47 implementation class to load: •

Use the javax.xml.parsers.SAXParserFactory system property.



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JAXP implementation and it's values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.



Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.parsers.SAXParserFactory in jars available to the runtime.



Platform default SAXParserFactory47 instance.

Once an application has obtained a reference to a SAXParserFactory47 it can use the factory to configure and obtain parser instances.

Tip for Trouble-shooting Setting the jaxp.debug system property will cause this method to print a lot of debug messages to

System.err about what it is doing and where it is looking at. If you have problems loading javax.xml.parsers.DocumentBuilder [ Class DocumentBuilder]s, try:

java -Djaxp.debug=1 YourProgram ....

Method newSAXParser() public SAXParser abstract newSAXParser()     throws ParserConfigurationException, org.xml.sax.SAXException;

50

Final 1.0.0

Package javax.xml.parsers

Exceptions ParserConfigurationExcep  tion

if a parser cannot be created which satisfies the requested configuration.

SAXException

for SAX errors.

Creates a new instance of a SAXParser using the currently configured factory parameters.

Method setFeature(String, boolean)

public void abstract setFeature(java.lang.String name,                                   boolean value)     throws ParserConfigurationException, org.xml.sax.SAXNotRecognizedException, org.xml.sax

Parameters name

The name of the feature to be set.

value

The value of the feature to be set.

Exceptions ParserConfigurationExcep  tion

if a parser cannot be created which satisfies the requested configuration.

SAXNotRecognizedEx  ception

When the underlying XMLReader does not recognize the property name.

SAXNotSupportedExcep  tion

When the underlying XMLReader recognizes the property name but doesn't support the property.

NullPointerException

If the name parameter is null.

See Also

org.xml.sax.XMLReader.setFeature

Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader. A list of the core features and properties can be found at http://www.saxproject.org/ All implementations are required to support the javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING feature. When the feature is •

true: the implementation will limit XML processing to conform to implementation limits. Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources. If XML processing is limited for security reasons, it will be reported via a call to the registered org.xml.sax.ErrorHandler.fatalError. See javax.xml.parsers.SAXParser [ Class SAXParser] parse methods for handler specification.



When the feature is false, the implementation will processing XML according to the XML specifications without regard to possible implementation limits.

Method setNamespaceAware(boolean) public void setNamespaceAware(boolean awareness);

51

Final 1.0.0

Package javax.xml.parsers

Parameters awareness

true if the parser produced by this code will provide support for XML namespaces; false other  wise.

Specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false.

Method setSchema(Schema) public void setSchema(javax.xml.validation.Schema schema);

Parameters schema

Schema156 to use, null to remove a schema.

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Set the javax.xml.validation.Schema to be used by parsers created from this factory. When a javax.xml.validation.Schema is non-null, a parser will use a validator created from it to validate documents before it passes information down to the application. When warnings/errors/fatal errors are found by the validator, the parser must handle them as if those errors were found by the parser itself. In other words, if the user-specified org.xml.sax.ErrorHandler is set, it must receive those errors, and if not, they must be treated according to the implementation specific default error handling rules. A validator may modify the SAX event stream (for example by adding default values that were missing in documents), and a parser is responsible to make sure that the application will receive those modified event stream. Initialy, null is set as the javax.xml.validation.Schema. This processing will take effect even if the javax.xml.parsers.SAXParserFactory.isValidating [ Method isValidating()] method returns false. It is an error to use the http://java.sun.com/xml/jaxp/properties/schemaSource property and/or the http://java.sun.com/xml/jaxp/properties/schemaLanguage property in conjunction with a non-null javax.xml.validation.Schema object. Such configuration will cause a org.xml.sax.SAXException exception when those properties are set on a javax.xml.parsers.SAXParser [ Class SAXParser].

Note for implmentors A parser must be able to work with any javax.xml.validation.Schema implementation. However, parsers and schemas are allowed to use implementation-specific custom mechanisms as long as they yield the result described in the spe  cification.

Method setValidating(boolean) public void setValidating(boolean validating);

52

Final 1.0.0

Package javax.xml.parsers

Parameters validating

true if the parser produced by this code will validate documents as they are parsed; false oth  erwise.

Specifies that the parser produced by this code will validate documents as they are parsed. By default the value of this is set to false. Note that "the validation" here means a validating parser [http://www.w3.org/TR/REC-xml#proc-types] as defined in the XML recommendation. In other words, it essentially just controls the DTD validation. (except the legacy two properties defined in JAXP 1.2. See here [#validationCompatibility] for more details.) To use modern schema languages such as W3C XML Schema or RELAX NG instead of DTD, you can configure your parser to be a non-validating parser by leaving the javax.xml.parsers.SAXParserFactory.setValidating [ Method setValidating(boolean)] method

false , then use the javax.xml.parsers.SAXParserFactory.setSchema [ Method setSchema(javax.xml.validation.Schema)] method to associate a schema to a parser.

Method setXIncludeAware(boolean) public void setXIncludeAware(boolean state);

Parameters state

Set XInclude processing to true or false

Exceptions UnsupportedOperationEx  ception Since

For backward compatibility, when implementations for earlier versions of JAXP is used, this exception will be thrown.

1.5

Set state of XInclude processing. If XInclude markup is found in the document instance, should it be processed as specified in XML Inclusions (XInclude) Version 1.0 [http://www.w3.org/TR/xinclude/]. XInclude processing defaults to false.

Exception ParserConfigurationException Indicates a serious configuration error.

Synopsis public ParserConfigurationException extends Exception { public ParserConfigurationException();

53

Final 1.0.0

Package javax.xml.parsers

public ParserConfigurationException(java.lang.String msg); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.2 $, $Date: 2003/12/06 00:21:41 $

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.parsers.ParserConfigurationException

Members Constructor ParserConfigurationException() public ParserConfigurationException(); Create a new ParserConfigurationException with no detail mesage.

Constructor ParserConfigurationException(String) public ParserConfigurationException(java.lang.String msg);

Parameters msg

The error message for the exception.

Create a new ParserConfigurationException with the String specified as an error message.

Error FactoryConfigurationError Thrown when a problem with configuration with the Parser Factories exists. This error will typically be thrown when the class of a parser factory specified in the system properties cannot be found or instantiated.

Synopsis public FactoryConfigurationError extends Error { public FactoryConfigurationError(); public FactoryConfigurationError(java.lang.String msg); public FactoryConfigurationError(java.lang.Exception e);

54

Final 1.0.0

Package javax.xml.parsers

public FactoryConfigurationError(java.lang.Exception e,                                    java.lang.String msg); public String getMessage(); public Exception getException(); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.2 $, $Date: 2003/12/06 00:21:42 $

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Error | javax.xml.parsers.FactoryConfigurationError

Members Constructor FactoryConfigurationError() public FactoryConfigurationError(); Create a new FactoryConfigurationError with no detail mesage.

Constructor FactoryConfigurationError(Exception) public FactoryConfigurationError(java.lang.Exception e);

Parameters e The exception to be encapsulated in a FactoryConfigurationError. Create a new FactoryConfigurationError with a given Exception base cause of the error.

Constructor FactoryConfigurationError(Exception, String) public FactoryConfigurationError(java.lang.Exception e,                                    java.lang.String msg);

Parameters e

The exception to be encapsulated in a FactoryConfigurationError

msg

The detail message.

55

Final 1.0.0

Package javax.xml.parsers

Create a new FactoryConfigurationError with the given Exception base cause and detail message.

Constructor FactoryConfigurationError(String) public FactoryConfigurationError(java.lang.String msg);

Parameters msg

The error message for the exception.

Create a new FactoryConfigurationError with the String specified as an error message.

Method getException() public Exception getException(); Return the actual exception (if any) that caused this exception to be raised.

Method getMessage() public String getMessage(); Return the message (if any) for this error . If there is no message for the exception and there is an encapsulated exception then the message of that exception, if it exists will be returned. Else the name of the encapsulated exception will be returned.

56

Final 1.0.0

Chapter 8. Package 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 javax.xml.transform.Source [ Interface Source] and javax.xml.transform.Result [ Interface 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 javax.xml.transform.sax [ Chapter 10, Package javax.xml.transform.sax], javax.xml.transform.dom [ Chapter 9, Package javax.xml.transform.dom], and javax.xml.transform.stream [ Chapter 11, Package javax.xml.transform.stream].

Creating Objects The API allows a concrete javax.xml.transform.TransformerFactory [ Class TransformerFactory] object to be created from the static function javax.xml.transform.TransformerFactory.newInstance [ Method newInstance()].

Specification of Inputs and Outputs This API defines two interface objects called javax.xml.transform.Source [ Interface Source] and javax.xml.trans  form.Result [ Interface 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: javax.xml.transform.stream.StreamSource [ Class StreamSource] and javax.xml.transform.stream.StreamResult [ Class StreamResult], javax.xml.transform.sax.SAX  Source [ Class SAXSource] and javax.xml.transform.sax.SAXResult [ Class SAXResult], and javax.xml.trans  form.dom.DOMSource [ Class DOMSource] and javax.xml.transform.dom.DOMResult [ Class DOMResult]. Each of these objects defines a FEATURE string (which is i the form of a URL), which can be passed into javax.xml.trans  form.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] 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 [http://www.w3.org/TR/REC-xml-names] 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 javax.xml.transform.Transformer [ Class Transformer] object, this specification defines that a String "qname" object

57

Final 1.0.0

Package javax.xml.transform

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 , 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 javax.xml.transform.Transformer.setOutputProp  erties [ Method setOutputProperties(java.util.Properties)] and the javax.xml.transform.Transformer.setOutputProperty [ Method setOutputProperty(java.lang.String, java.lang.String)] 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 [http://www.w3.org/TR/xslt#output] can be referenced from the javax.xml.transform.OutputKeys [ Class OutputKeys] class. Other strings can be specified as well. If the transformer does not recognize an output key, a java.lang.IllegalArgumentException is thrown, unless the key name is namespace qualified [#qname-delimiter]. 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 javax.xml.transform.Transformer  Factory [ Class TransformerFactory] provides a javax.xml.transform.TransformerFactory.newTransformer [ Method 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 javax.xml.transform.TransformerFactoryCon  figurationError [ Error TransformerFactoryConfigurationError] is parallel to the javax.xml.parsers.FactoryConfigura  tionError, 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 javax.xml.transform.TransformerConfigurationException [ Exception 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 javax.xml.transform.TransformerFact  ory.newTransformer [ Method newTransformer(javax.xml.transform.Source)] is called. javax.xml.transform.TransformerException [ Exception 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 javax.xml.transform.TransformerException.printStackTrace [ Method 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 javax.xml.transform.SourceLocator [ Interface SourceLocator] object which indicates where in the source tree or transformation instructions the error occurred. javax.xml.transform.TransformerException.getMessageAndLocation [ Method getMessageAndLocation()] may be called to get an error message with location info, and javax.xml.trans  form.TransformerException.getLocationAsString [ Method getLocationAsString()] may be called to get just the location string. Transformation warnings and errors are sent to an javax.xml.transform.ErrorListener [ Interface 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 javax.xml.transform.TransformerFactory.setErrorListener [ Method setErrorListener(javax.xml.transform.ErrorListener)] for reporting errors that have to do with syntax errors in

58

Final 1.0.0

Package javax.xml.transform

the transformation instructions, or via javax.xml.transform.Transformer.setErrorListener [ Method setErrorListen  er(javax.xml.transform.ErrorListener)] 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 Sys  tem.err and does not throw any Exceptions. Applications are strongly encouraged to register and use ErrorL  isteners 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 javax.xml.transform.URI  Resolver [ Interface URIResolver] interface, with its one method, javax.xml.transform.URIResolver.resolve [ Method resolve(java.lang.String, java.lang.String)], and use this class to set the URI resolution for the transformation instructions or transformation with javax.xml.transform.TransformerFactory.setURIResolver [ Method setURIResolv  er(javax.xml.transform.URIResolver)] or javax.xml.transform.Transformer.setURIResolver [ Method setURIResolv  er(javax.xml.transform.URIResolver)]. 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 javax.xml.transform.Source [ Interface Source] object must be usable by the transformer, as specified in its implemented features.

Class OutputKeys Provides string constants that can be used to set output properties for a Transformer, or to retrieve output properties from a Transformer or Templates object. All the fields in this class are read-only.

Synopsis public OutputKeys { } See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

(XSLT)

W3C

Recommendation.

Inheritance Path java.lang.Object | javax.xml.transform.OutputKeys

Members Field CDATA_SECTION_ELEMENTS   static java.lang.String CDATA_SECTION_ELEMENTS ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

cdata-section-elements = expanded names expanded names.

59

Final 1.0.0

Package javax.xml.transform

cdata-section-elements specifies a whitespace delimited list of the names of elements whose text node children should be output using CDATA sections. Note that these names must use the format described in the section Qualfied Name Representation in javax.xml.transform [ Chapter 8, Package javax.xml.transform].

Field DOCTYPE_PUBLIC   static java.lang.String DOCTYPE_PUBLIC ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

doctype-public = string string. See the documentation for the javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM [ Field DOCTYPE_SYSTEM] property for a description of what the value of the key should be.

Field DOCTYPE_SYSTEM   static java.lang.String DOCTYPE_SYSTEM ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

doctype-system = string string. doctype-system specifies the system identifier to be used in the document type declaration. If the doctype-system property is specified, the xml output method should output a document type declaration imme  diately before the first element. The name following
Field ENCODING   static java.lang.String ENCODING ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

encoding = string string. encoding specifies the preferred character encoding that the Transformer should use to encode sequences of characters as sequences of bytes. The value of the encoding property should be treated case-insensitively. The value must only

60

Final 1.0.0

Package javax.xml.transform

contain characters in the range #x21 to #x7E (i.e., printable ASCII characters). The value should either be a charset registered with the Internet Assigned Numbers Authority [IANA] [#IANA], [RFC2278] [#RFC2278] or start with X-.

Field INDENT   static java.lang.String INDENT ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

indent = "yes" | "no". indent specifies whether the Transformer may add additional whitespace when outputting the result tree; the value must be yes or no.

Field MEDIA_TYPE   static java.lang.String MEDIA_TYPE ; See Also

s ection 16 of the XSL [http://www.w3.org/TR/xslt#output]

Transformations

(XSLT)

W3C

Recommendation

media-type = string string. media-type specifies the media type (MIME content type) of the data that results from outputting the result tree. The charset parameter should not be specified explicitly; instead, when the top-level media type is text, a charset parameter should be added according to the character encoding actually used by the output method.

Field METHOD   static java.lang.String METHOD ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

method = "xml" | "html" | "text" | expanded name expanded name. The value of the method property identifies the overall method that should be used for outputting the result tree. Other non-namespaced values may be used, such as "xhtml", but, if accepted, the handling of such values is implementation defined. If any of the method values are not accepted and are not namespace qualified, then javax.xml.transform.Trans  former.setOutputProperty [ Method setOutputProperty(java.lang.String, java.lang.String)] or javax.xml.transform.Trans  former.setOutputProperties [ Method setOutputProperties(java.util.Properties)] will throw a java.lang.IllegalArgu  mentException.

Field OMIT_XML_DECLARATION   static java.lang.String OMIT_XML_DECLARATION ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

omit-xml-declaration = "yes" | "no". omit-xml-declaration specifies whether the XSLT processor should output an XML declaration; the value must be yes or no.

61

Final 1.0.0

Package javax.xml.transform

Field STANDALONE   static java.lang.String STANDALONE ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

standalone = "yes" | "no". standalone specifies whether the Transformer should output a standalone document declaration; the value must be yes or no.

Field VERSION   static java.lang.String VERSION ; See Also

section 16 of the XSL Transformations [http://www.w3.org/TR/xslt#output]

(XSLT)

W3C

Recommendation

version = nmtoken nmtoken. version specifies the version of the output method. When the output method is "xml", the version value specifies the version of XML to be used for outputting the result tree. The default value for the xml output method is 1.0. When the output method is "html", the version value indicates the version of the HTML. The default value for the xml output method is 4.0, which specifies that the result should be output as HTML conforming to the HTML 4.0 Recommendation [HTML]. If the output method is "text", the version property is ignored.

Class Transformer An instance of this abstract class can transform a source tree into a result tree. An instance of this class can be obtained with the TransformerFactory.newTransformer [ Method newTrans  former(javax.xml.transform.Source)] method. This instance may then be used to process XML from a variety of sources and write the transformation output to a variety of sinks. An object of this class may not be used in multiple threads running concurrently. Different Transformers may be used concurrently by different threads. A Transformer62 may be used multiple times. Parameters and output properties are preserved across transformations.

Synopsis public Transformer { protected Transformer(); public void reset(); public void abstract transform(javax.xml.transform.Source xmlSource,                                  javax.xml.transform.Result outputTarget)     throws TransformerException;

62

Final 1.0.0

Package javax.xml.transform

public void abstract setParameter(java.lang.String name,                                     java.lang.Object value); public Object abstract getParameter(java.lang.String name); public void abstract clearParameters(); public void abstract setURIResolver(javax.xml.transform.URIResolver resolver); public URIResolver abstract getURIResolver(); public void abstract setOutputProperties(java.util.Properties oformat); public Properties abstract getOutputProperties(); public void abstract setOutputProperty(java.lang.String name,                                          java.lang.String value)     throws java.lang.IllegalArgumentException; public String abstract getOutputProperty(java.lang.String name)     throws java.lang.IllegalArgumentException; public void abstract setErrorListener(javax.xml.transform.ErrorListener listener)     throws java.lang.IllegalArgumentException; public ErrorListener abstract getErrorListener(); } Author

Jeff Suttor [[email protected]]

Version

$Revision: 1.9.14.1.2.4 $, $Date: 2004/06/28 18:45:41 $

Inheritance Path java.lang.Object | javax.xml.transform.Transformer

Members Constructor Transformer() protected Transformer(); Default constructor is protected on purpose.

Method clearParameters() public void abstract clearParameters(); Clear all parameters set with setParameter.

63

Final 1.0.0

Package javax.xml.transform

Method getErrorListener() public ErrorListener abstract getErrorListener(); Get the error event handler in effect for the transformation. Implementations must provide a default error listener.

Method getOutputProperties() public Properties abstract getOutputProperties(); See Also

javax.xml.transform.OutputKeys [Class OutputKeys], java.util.Properties, XSL Transformations (XSLT) Version 1.0 [http://www.w3.org/TR/xslt#output]

Get a copy of the output properties for the transformation. The properties returned should contain properties set by the user, and properties set by the stylesheet, and these prop  erties are "defaulted" by default properties specified by section 16 of the XSL Transformations (XSLT) W3C Recom  mendation [http://www.w3.org/TR/xslt#output]. The properties that were specifically set by the user or the stylesheet should be in the base Properties list, while the XSLT default properties that were not specifically set should be the default Properties list. Thus, getOutputProperties().getProperty(String key) will obtain any property in that was set by javax.xml.transform.Transformer.setOutputProperty [ Method setOutputProperty(java.lang.String, java.lang.String)], javax.xml.transform.Transformer.setOutputProperties [ Method setOutputProperties(java.util.Properties)], in the stylesheet, or the default properties, while getOutputProperties().get(String key) will only retrieve properties that were explicitly set by javax.xml.transform.Transformer.setOutputProperty [ Method setOutputProperty(java.lang.String, java.lang.String)], javax.xml.transform.Transformer.setOutputProperties [ Method setOutputProperties(java.util.Prop  erties)], or in the stylesheet. Note that mutation of the Properties object returned will not effect the properties that the transformer contains. If any of the argument keys are not recognized and are not namespace qualified, the property will be ignored and not returned. In other words the behaviour is not orthogonal with setOutputProperties [ Method setOutputProper  ties(java.util.Properties)].

Method getOutputProperty(String) public String abstract getOutputProperty(java.lang.String name)     throws java.lang.IllegalArgumentException;

Parameters name

A non-null String that specifies an output property name, which may be namespace qualified.

returns

The string value of the output property, or null if no property was found.

Exceptions IllegalArgumentException See Also

If the property is not supported.

javax.xml.transform.OutputKeys [Class OutputKeys]

Get an output property that is in effect for the transformer. The property specified may be a property that was set with setOutputProperty, or it may be a property specified in the stylesheet.

64

Final 1.0.0

Package javax.xml.transform

Method getParameter(String) public Object abstract getParameter(java.lang.String name);

Parameters name

of Object to get

returns

A parameter that has been set with setParameter.

Get a parameter that was explicitly set with setParameter. This method does not return a default parameter value, which cannot be determined until the node context is evaluated during the transformation process.

Method getURIResolver() public URIResolver abstract getURIResolver(); Get an object that will be used to resolve URIs used in document().

Method reset() public void reset(); Since

1.5

Reset this Transformer62 to its original configuration. Transformer62 is reset to the same state as when it was created with javax.xml.transform.TransformerFact  ory.newTransformer [ Method newTransformer()], javax.xml.transform.TransformerFactory.newTransformer [ Method newTransformer(javax.xml.transform.Source)] or javax.xml.transform.Templates.newTransformer [ Method newTransformer()]. reset() is designed to allow the reuse of existing Transformer62s thus saving resources as  sociated with the creation of new Transformer62s. The reset Transformer62 is not guaranteed to have the same javax.xml.transform.URIResolver [ Interface URIRe  solver] or javax.xml.transform.ErrorListener [ Interface ErrorListener] Objects, e.g. java.lang.Object.equals. It is guaranteed to have a functionally equal URIResolver and ErrorListener.

Method setErrorListener(ErrorListener) public void abstract setErrorListener(javax.xml.transform.ErrorListener listener)     throws java.lang.IllegalArgumentException;

Parameters listener

The new error listener.

Exceptions IllegalArgumentException

if listener is null.

Set the error event listener in effect for the transformation.

65

Final 1.0.0

Package javax.xml.transform

Method setOutputProperties(Properties) public void abstract setOutputProperties(java.util.Properties oformat);

Parameters oformat

A set of output properties that will be used to override any of the same properties in affect for the transformation.

See Also

javax.xml.transform.OutputKeys [Class OutputKeys], java.util.Properties

Set the output properties for the transformation. These properties will override properties set in the Templates with xsl:output. If argument to this function is null, any properties previously set are removed, and the value will revert to the value defined in the templates object. Pass a qualified property key name as a two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the name has a null URL, the String only contain 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 , then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that no prefix is used. An IllegalArgumentException is thrown if any of the argument keys are not recognized and are not namespace qualified.

Method setOutputProperty(String, String) public void abstract setOutputProperty(java.lang.String name,                                          java.lang.String value)     throws java.lang.IllegalArgumentException;

Parameters name

A non-null String that specifies an output property name, which may be namespace qualified.

value

The non-null string value of the output property.

Exceptions IllegalArgumentException See Also

If the property is not supported, and is not qualified with a namespace.

javax.xml.transform.OutputKeys [Class OutputKeys]

Set an output property that will be in effect for the transformation. Pass a qualified property name as a two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the name has a null URL, the String only contain 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 , then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that no prefix is used.

66

Final 1.0.0

Package javax.xml.transform

The Properties object that was passed to javax.xml.transform.Transformer.setOutputProperties [ Method setOutput  Properties(java.util.Properties)] won't be effected by calling this method.

Method setParameter(String, Object) public void abstract setParameter(java.lang.String name,                                     java.lang.Object value);

Parameters name

The name of the parameter, which may begin with a namespace URI in curly braces ({}).

value

The value object. This can be any valid Java object. It is up to the processor to provide the proper object coersion or to simply pass the object on for use in an extension.

Exceptions NullPointerException

If value is null.

Add a parameter for the transformation. Pass a qualified name as a two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the name has a null URL, the String only contain the local name. An application can safely check for a nonnull 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 , then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that no prefix is used.

Method setURIResolver(URIResolver) public void abstract setURIResolver(javax.xml.transform.URIResolver resolver);

Parameters resolver

An object that implements the URIResolver interface, or null.

Set an object that will be used to resolve URIs used in document(). If the resolver argument is null, the URIResolver value will be cleared and the transformer will no longer have a resolver.

Method transform(Source, Result) public void abstract transform(javax.xml.transform.Source xmlSource,                                  javax.xml.transform.Result outputTarget)     throws TransformerException;

Parameters xmlSource

The XML input to transform.

outputTarget

The Result of transforming the xmlSource.

67

Final 1.0.0

Package javax.xml.transform

Exceptions TransformerException

If an unrecoverable error occurs during the course of the transformation.

Transform the XML Source to a Result. Specific transformation behavior is determined by the settings of the TransformerFactory68 in effect when the Transformer62 was instantiated and any modifications made to the Transformer62 instance. An empty Source is represented as an empty document as constructed by javax.xml.parsers.DocumentBuilder#new  Document(). The result of transforming an empty Source depends on the transformation behavior; it is not always an empty Result.

Class TransformerFactory A TransformerFactory instance can be used to create javax.xml.transform.Transformer [ Class Transformer] and javax.xml.transform.Templates [ Interface Templates] objects. The system property that determines which Factory implementation to create is named "javax.xml.trans  form.TransformerFactory". This property names a concrete subclass of the TransformerFactory68 abstract class. If the property is not defined, a platform default is be used.

Synopsis public TransformerFactory { protected TransformerFactory(); static TransformerFactory newInstance()     throws TransformerFactoryConfigurationError; public Transformer abstract newTransformer(javax.xml.transform.Source source)     throws TransformerConfigurationException; public Transformer abstract newTransformer()     throws TransformerConfigurationException; public Templates abstract newTemplates(javax.xml.transform.Source source)     throws TransformerConfigurationException; public Source abstract getAssociatedStylesheet(javax.xml.transform.Source source,                                                  java.lang.String media,                                                  java.lang.String title,                                                  java.lang.String charset)     throws TransformerConfigurationException; public void abstract setURIResolver(javax.xml.transform.URIResolver resolver); public URIResolver abstract getURIResolver(); public void abstract setFeature(java.lang.String name,                                   boolean value)     throws TransformerConfigurationException; public boolean abstract getFeature(java.lang.String name);

68

Final 1.0.0

Package javax.xml.transform

public void abstract setAttribute(java.lang.String name,                                     java.lang.Object value); public Object abstract getAttribute(java.lang.String name); public void abstract setErrorListener(javax.xml.transform.ErrorListener listener); public ErrorListener abstract getErrorListener(); } Author

Jeff Suttor [mailto:[email protected]]

Inheritance Path java.lang.Object | javax.xml.transform.TransformerFactory

Members Constructor TransformerFactory() protected TransformerFactory(); Default constructor is protected on purpose.

Method getAssociatedStylesheet(Source, String, String, String) public Source abstract getAssociatedStylesheet(javax.xml.transform.Source source,                                                  java.lang.String media,                                                  java.lang.String title,                                                  java.lang.String charset)     throws TransformerConfigurationException;

Parameters source

The XML source document.

media

The media attribute to be matched. May be null, in which case the prefered templates will be used (i.e. alternate = no).

title

The value of the title attribute to match. May be null.

charset

The value of the charset attribute to match. May be null.

returns

A Source Object suitable for passing to the TransformerFactory68.

Exceptions TransformerConfigura  tionException See Also

An Exception is thrown if an error occurings during parsing of the source.

Associating Style Sheets with XML documents Version 1.0 [http://www.w3.org/TR/xml-stylesheet/]

69

Final 1.0.0

Package javax.xml.transform

Get the stylesheet specification(s) associated with the XML Source document via the xml-stylesheet processing in  struction [http://www.w3.org/TR/xml-stylesheet/] that match the given criteria. Note that it is possible to return several stylesheets, in which case they are applied as if they were a list of imports or cascades in a single stylesheet.

Method getAttribute(String) public Object abstract getAttribute(java.lang.String name);

Parameters name

The name of the attribute.

returns

value The value of the attribute.

Allows the user to retrieve specific attributes on the underlying implementation. An IllegalArgumentException is thrown if the underlying implementation doesn't recognize the attribute.

Method getErrorListener() public ErrorListener abstract getErrorListener(); Get the error event handler for the TransformerFactory.

Method getFeature(String) public boolean abstract getFeature(java.lang.String name);

Parameters name

Feature name.

returns

The current state of the feature, true or false.

Exceptions NullPointerException

If the name parameter is null.

Look up the value of a feature. Feature names are fully qualified java.net.URIs. Implementations may define their own features. false is returned if this TransformerFactory68 or the Transformer62s or Templates it creates cannot support the feature. It is possible for an TransformerFactory68 to expose a feature value but be unable to change its state.

Method getURIResolver() public URIResolver abstract getURIResolver(); Get the object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.

Method newInstance() static TransformerFactory newInstance()     throws TransformerFactoryConfigurationError;

70

Final 1.0.0

Package javax.xml.transform

Exceptions TransformerFactoryCon  figurationError

Thrown if the implementation is not available or cannot be instantiated.

Obtain a new instance of a TransformerFactory68. This static method creates a new factory instance This method uses the following ordered lookup procedure to determine the TransformerFactory68 implementation class to load: •

Use the javax.xml.transform.TransformerFactory system property.



Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JAXP implementation and it's values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.



Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.transform.Transformer  Factory in jars available to the runtime.



Platform default TransformerFactory68 instance.

Once an application has obtained a reference to a TransformerFactory it can use the factory to configure and obtain parser instances.

Method newTemplates(Source) public Templates abstract newTemplates(javax.xml.transform.Source source)     throws TransformerConfigurationException;

Parameters source

An object that holds a URL, input stream, etc.

returns

A Templates object capable of being used for transformation purposes, never null.

Exceptions TransformerConfigura  tionException

May throw this during the parse when it is constructing the Templates object and fails.

Process the Source into a Templates object, which is a a compiled representation of the source. This Templates object may then be used concurrently across multiple threads. Creating a Templates object allows the TransformerFactory to do detailed performance optimization of transformation instructions, without penalizing runtime transformation.

Method newTransformer() public Transformer abstract newTransformer()     throws TransformerConfigurationException;

71

Final 1.0.0

Package javax.xml.transform

Exceptions TransformerConfigura  tionException

Thrown if it is not possible to create a Transformer62 instance.

Create a new Transformer that performs a copy of the Source to the Result. i.e. the "identity transform".

Method newTransformer(Source) public Transformer abstract newTransformer(javax.xml.transform.Source source)     throws TransformerConfigurationException;

Parameters source

Source of XSLT document used to create Transformer62. Examples of XML Sources include DOMSource [ Class DOMSource], SAXSource [ Class SAXSource], and StreamSource [ Class StreamSource].

returns

A Transformer62 object that may be used to perform a transformation in a single Thread, never null.

Exceptions TransformerConfigura  tionException See Also

Thrown if there are errors when parsing the Source or it is not possible to create a Transformer62 instance.

XSL Transformations (XSLT) Version 1.0 [http://www.w3.org/TR/xslt]

Process the Source into a Transformer62 Object. The Source is an XSLT document that conforms to XSL Transformations (XSLT) Version 1.0 [http://www.w3.org/TR/xslt]. Care must be taken not to use this Transformer 62 in multiple Threads running concurrently. Different TransformerFactories can be used concurrently by different Threads.

Method setAttribute(String, Object) public void abstract setAttribute(java.lang.String name,                                     java.lang.Object value);

Parameters name

The name of the attribute.

value

The value of the attribute.

Allows the user to set specific attributes on the underlying implementation. An attribute in this context is defined to be an option that the implementation provides. An IllegalArgumentException is thrown if the underlying implementation doesn't recognize the attribute.

Method setErrorListener(ErrorListener) public void abstract setErrorListener(javax.xml.transform.ErrorListener listener);

72

Final 1.0.0

Package javax.xml.transform

Parameters listener

The new error listener.

Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself. An IllegalArgumentException is thrown if the ErrorListener listener is null.

Method setFeature(String, boolean) public void abstract setFeature(java.lang.String name,                                   boolean value)     throws TransformerConfigurationException;

Parameters name

Feature name.

value

Is feature state true or false.

Exceptions TransformerConfigura  tionException

if this TransformerFactory68 or the Transformer62s or Templates it creates cannot support this feature.

NullPointerException

If the name parameter is null.

Set a feature for this TransformerFactory68 and Transformer62s or Templates created by this factory. Feature names are fully qualified java.net.URIs. Implementations may define their own features. An javax.xml.trans  form.TransformerConfigurationException [ Exception TransformerConfigurationException] is thrown if this Trans  formerFactory68 or the Transformer62s or Templates it creates cannot support the feature. It is possible for an TransformerFactory68 to expose a feature value but be unable to change its state. All implementations are required to support the javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING feature. When the feature is: •

true: the implementation will limit XML processing to conform to implementation limits and behave in a secure fashion as defined by the implementation. Examples include resolving user defined style sheets and functions. If XML processing is limited for security reasons, it will be reported via a call to the registered javax.xml.transform.Er  rorListener.fatalError [ Method fatalError(javax.xml.transform.TransformerException)]. See javax.xml.trans  form.TransformerFactory.setErrorListener [ Method setErrorListener(javax.xml.transform.ErrorListener)].



false: the implementation will processing XML according to the XML specifications without regard to possible implementation limits.

Method setURIResolver(URIResolver) public void abstract setURIResolver(javax.xml.transform.URIResolver resolver);

Parameters resolver

An object that implements the URIResolver interface, or null.

73

Final 1.0.0

Package javax.xml.transform

Set an object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.

Interface ErrorListener To provide customized error handling, implement this interface and use the setErrorListener method to register an instance of the implmentation with the javax.xml.transform.Transformer [ Class Transformer]. The Transformer 62 then reports all errors and warnings through this interface. If an application does not register its own custom ErrorListener, the default ErrorListener is used which reports 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. For transformation errors, a Transformer62 must use this interface instead of throwing an Exception: it is up to the application to decide whether to throw an Exception for different types of errors and warnings. Note however that the Transformer62 is not required to continue with the transformation after a call to javax.xml.transform.Er  rorListener.fatalError [ Method fatalError(javax.xml.transform.TransformerException)]. Transformer62s may use this mechanism to report XML parsing errors as well as transformation errors.

Synopsis implements public ErrorListener { public void warning(javax.xml.transform.TransformerException exception)     throws TransformerException; public void error(javax.xml.transform.TransformerException exception)     throws TransformerException; public void fatalError(javax.xml.transform.TransformerException exception)     throws TransformerException; } Inheritance Path javax.xml.transform.ErrorListener

Members Method error(TransformerException) public void error(javax.xml.transform.TransformerException exception)     throws TransformerException;

Parameters exception

The error information encapsulated in a transformer exception.

74

Final 1.0.0

Package javax.xml.transform

Exceptions javax.xml.transform.Trans  formerException See Also

if the application chooses to discontinue the transformation.

javax.xml.transform.TransformerException [Exception TransformerException]

Receive notification of a recoverable error. The transformer must continue to try and provide normal transformation after invoking this method. It should still be possible for the application to process the document through to the end if no other errors are encountered.

Method fatalError(TransformerException) public void fatalError(javax.xml.transform.TransformerException exception)     throws TransformerException;

Parameters exception

The error information encapsulated in a TransformerException.

Exceptions javax.xml.transform.Trans  formerException See Also

if the application chooses to discontinue the transformation.

javax.xml.transform.TransformerException [Exception TransformerException]

Receive notification of a non-recoverable error. The Transformer62 must continue to try and provide normal transformation after invoking this method. It should still be possible for the application to process the document through to the end if no other errors are encountered, but there is no guarantee that the output will be useable.

Method warning(TransformerException) public void warning(javax.xml.transform.TransformerException exception)     throws TransformerException;

Parameters exception

The warning information encapsulated in a transformer exception.

Exceptions javax.xml.transform.Trans  formerException See Also

if the application chooses to discontinue the transformation.

javax.xml.transform.TransformerException [Exception TransformerException]

Receive notification of a warning. javax.xml.transform.Transformer [ Class Transformer] can use this method to report conditions that are not errors or fatal errors. The default behaviour is to take no action.

75

Final 1.0.0

Package javax.xml.transform

After invoking this method, the Transformer must continue with the transformation. It should still be possible for the application to process the document through to the end.

Interface Result An object that implements this interface contains the information needed to build a transformation result tree.

Synopsis implements public Result { public void setSystemId(java.lang.String systemId); public String getSystemId(); } Author

Jeff Suttor [[email protected]]

Inheritance Path javax.xml.transform.Result

Members Field PI_DISABLE_OUTPUT_ESCAPING   static java.lang.String PI_DISABLE_OUTPUT_ESCAPING ; See Also

disable-output-escaping in XSLT Specification [http://www.w3.org/TR/xslt#disable-output-escaping]

The name of the processing instruction that is sent if the result tree disables output escaping. Normally, result tree serialization escapes & and < (and possibly other characters) when outputting text nodes. This ensures that the output is well-formed XML. However, it is sometimes convenient to be able to produce output that is almost, but not quite well-formed XML; for example, the output may include ill-formed sections that will be transformed into well-formed XML by a subsequent non-XML aware process. If a processing instruction is sent with this name, serialization should be output without any escaping. Result DOM trees may also have PI_DISABLE_OUTPUT_ESCAPING and PI_ENABLE_OUTPUT_ESCAPING inserted into the tree.

Field PI_ENABLE_OUTPUT_ESCAPING   static java.lang.String PI_ENABLE_OUTPUT_ESCAPING ; See Also

disable-output-escaping in XSLT Specification [http://www.w3.org/TR/xslt#disable-output-escaping]

The name of the processing instruction that is sent if the result tree enables output escaping at some point after having received a PI_DISABLE_OUTPUT_ESCAPING processing instruction.

Method getSystemId() public String getSystemId();

76

Final 1.0.0

Package javax.xml.transform

Get the system identifier that was set with setSystemId.

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URI string.

Set the system identifier for this Result. If the Result is not to be written to a file, the system identifier is optional. The application may still want to provide one, however, for use in error messages and warnings, or to resolve relative output identifiers.

Interface Source An object that implements this interface contains the information needed to act as source input (XML source or trans  formation instructions).

Synopsis implements public Source { public void setSystemId(java.lang.String systemId); public String getSystemId(); } Inheritance Path javax.xml.transform.Source

Members Method getSystemId() public String getSystemId(); Get the system identifier that was set with setSystemId.

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URL string.

Set the system identifier for this Source.

77

Final 1.0.0

Package javax.xml.transform

The system identifier is optional if the source does not get its data from a URL, but it may still be useful to provide one. The application can use a system identifier, for example, to resolve relative URIs and to include in error messages and warnings.

Interface SourceLocator This interface is primarily for the purposes of reporting where an error occurred in the XML source or transformation instructions.

Synopsis implements public SourceLocator { public String getPublicId(); public String getSystemId(); public int getLineNumber(); public int getColumnNumber(); } Inheritance Path javax.xml.transform.SourceLocator

Members Method getColumnNumber() public int getColumnNumber(); See Also

javax.xml.transform.SourceLocator.getLineNumber [Method getLineNumber()]

Return the character position where the current document event ends. Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document. The return value is an approximation of the column number in the document entity or external parsed entity where the markup that triggered the event appears.

Method getLineNumber() public int getLineNumber(); See Also

javax.xml.transform.SourceLocator.getColumnNumber [Method getColumnNumber()]

Return the line number where the current document event ends. Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

78

Final 1.0.0

Package javax.xml.transform

The return value is an approximation of the line number in the document entity or external parsed entity where the markup that triggered the event appears.

Method getPublicId() public String getPublicId(); See Also

javax.xml.transform.SourceLocator.getSystemId [Method getSystemId()]

Return the public identifier for the current document event. The return value is the public identifier of the document entity or of the external parsed entity in which the markup that triggered the event appears.

Method getSystemId() public String getSystemId(); See Also

javax.xml.transform.SourceLocator.getPublicId [Method getPublicId()]

Return the system identifier for the current document event. The return value is the system identifier of the document entity or of the external parsed entity in which the markup that triggered the event appears. If the system identifier is a URL, the parser must resolve it fully before passing it to the application.

Interface Templates An object that implements this interface is the runtime representation of processed transformation instructions. Templates must be threadsafe for a given instance over multiple threads running concurrently, and may be used multiple times in a given session.

Synopsis implements public Templates { public Transformer newTransformer()     throws TransformerConfigurationException; public Properties getOutputProperties(); } Inheritance Path javax.xml.transform.Templates

Members Method getOutputProperties() public Properties getOutputProperties();

79

Final 1.0.0

Package javax.xml.transform

Get the properties corresponding to the effective xsl:output element. The object returned will be a clone of the internal values. Accordingly, it can be mutated without mutating the Templates object, and then handed in to javax.xml.trans  form.Transformer.setOutputProperties [ Method setOutputProperties(java.util.Properties)]. The properties returned should contain properties set by the stylesheet, and these properties are "defaulted" by default properties specified by section 16 of the XSL Transformations (XSLT) W3C Recommendation [http://www.w3.org/TR/xslt#output]. The properties that were specifically set by the stylesheet should be in the base Properties list, while the XSLT default properties that were not specifically set should be in the "default" Properties list. Thus, getOutputProperties().getProperty(String key) will obtain any property in that was set by the stylesheet, or the default properties, while getOutputProperties().get(String key) will only retrieve properties that were explicitly set in the stylesheet. For XSLT, Attribute Value Templates [http://www.w3.org/TR/xslt#attribute-value-templates] attribute values will be returned unexpanded (since there is no context at this point). The namespace prefixes inside Attribute Value Templates will be unexpanded, so that they remain valid XPath values.

Method newTransformer() public Transformer newTransformer()     throws TransformerConfigurationException;

Exceptions TransformerConfigura  tionException

if a Transformer can not be created.

Create a new transformation context for this Templates object.

Interface URIResolver An object that implements this interface that can be called by the processor to turn a URI used in document(), xsl:import, or xsl:include into a Source object.

Synopsis implements public URIResolver { public Source resolve(java.lang.String href,                         java.lang.String base)     throws TransformerException; } Inheritance Path javax.xml.transform.URIResolver

80

Final 1.0.0

Package javax.xml.transform

Members Method resolve(String, String) public Source resolve(java.lang.String href,                         java.lang.String base)     throws TransformerException;

Parameters href

An href attribute, which may be relative or absolute.

base

The base URI against which the first argument will be made absolute if the absolute URI is required.

returns

A Source object, or null if the href cannot be resolved, and the processor should try to resolve the URI itself.

Exceptions TransformerException

if an error occurs when trying to resolve the URI.

Called by the processor when it encounters an xsl:include, xsl:import, or document() function.

Exception TransformerConfigurationException Indicates a serious configuration error.

Synopsis public TransformerConfigurationException extends TransformerException { public TransformerConfigurationException(); public TransformerConfigurationException(java.lang.String msg); public TransformerConfigurationException(java.lang.Throwable e); public TransformerConfigurationException(java.lang.String msg,                                            java.lang.Throwable e); public TransformerConfigurationException(java.lang.String message,                                            javax.xml.transform.SourceLocator locator); public TransformerConfigurationException(java.lang.String message,                                            javax.xml.transform.SourceLocator locator,                                            java.lang.Throwable e); } Inheritance Path java.lang.Object |

81

Final 1.0.0

Package javax.xml.transform

Inheritance Path java.lang.Throwable | java.lang.Exception | javax.xml.transform.TransformerException | javax.xml.transform.TransformerConfigurationException

Members Constructor TransformerConfigurationException() public TransformerConfigurationException(); Create a new TransformerConfigurationException with no detail mesage.

Constructor TransformerConfigurationException(String) public TransformerConfigurationException(java.lang.String msg);

Parameters msg

The error message for the exception.

Create a new TransformerConfigurationException with the String specified as an error message.

Constructor TransformerConfigurationException(String, SourceLocator) public TransformerConfigurationException(java.lang.String message,                                            javax.xml.transform.SourceLocator locator);

Parameters message

The error or warning message.

locator

The locator object for the error or warning.

Create a new TransformerConfigurationException from a message and a Locator. This constructor is especially useful when an application is creating its own exception from within a DocumentHandler callback.

Constructor Throwable)

TransformerConfigurationException(String,

SourceLocator,

public TransformerConfigurationException(java.lang.String message,                                            javax.xml.transform.SourceLocator locator,                                            java.lang.Throwable e);

82

Final 1.0.0

Package javax.xml.transform

Parameters message

The error or warning message, or null to use the message from the embedded exception.

locator

The locator object for the error or warning.

e

Any exception.

Wrap an existing exception in a TransformerConfigurationException.

Constructor TransformerConfigurationException(String, Throwable) public TransformerConfigurationException(java.lang.String msg,                                            java.lang.Throwable e);

Parameters e

The exception to be encapsulated in a TransformerConfigurationException

msg

The detail message.

Create a new TransformerConfigurationException with the given Exception base cause and detail message.

Constructor TransformerConfigurationException(Throwable) public TransformerConfigurationException(java.lang.Throwable e);

Parameters e The exception to be encapsulated in a TransformerConfigurationException. Create a new TransformerConfigurationException with a given Exception base cause of the error.

Exception TransformerException This class specifies an exceptional condition that occured during the transformation process.

Synopsis public TransformerException extends Exception { public TransformerException(java.lang.String message); public TransformerException(java.lang.Throwable e); public TransformerException(java.lang.String message,                               java.lang.Throwable e); public TransformerException(java.lang.String message,                               javax.xml.transform.SourceLocator locator);

83

Final 1.0.0

Package javax.xml.transform

public TransformerException(java.lang.String message,                               javax.xml.transform.SourceLocator locator,                               java.lang.Throwable e); public SourceLocator getLocator(); public void setLocator(javax.xml.transform.SourceLocator location); public Throwable getException(); public Throwable getCause(); public Throwable initCause(java.lang.Throwable cause); public String getMessageAndLocation(); public String getLocationAsString(); public void printStackTrace(); public void printStackTrace(java.io.PrintStream s); public void printStackTrace(java.io.PrintWriter s); } Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.transform.TransformerException

Members Constructor TransformerException(String) public TransformerException(java.lang.String message);

Parameters message

The error or warning message.

Create a new TransformerException.

Constructor TransformerException(String, SourceLocator) public TransformerException(java.lang.String message,                               javax.xml.transform.SourceLocator locator);

84

Final 1.0.0

Package javax.xml.transform

Parameters message

The error or warning message.

locator

The locator object for the error or warning.

Create a new TransformerException from a message and a Locator. This constructor is especially useful when an application is creating its own exception from within a DocumentHandler callback.

Constructor TransformerException(String, SourceLocator, Throwable) public TransformerException(java.lang.String message,                               javax.xml.transform.SourceLocator locator,                               java.lang.Throwable e);

Parameters message

The error or warning message, or null to use the message from the embedded exception.

locator

The locator object for the error or warning.

e

Any exception

Wrap an existing exception in a TransformerException.

Constructor TransformerException(String, Throwable) public TransformerException(java.lang.String message,                               java.lang.Throwable e);

Parameters message

The error or warning message, or null to use the message from the embedded exception.

e

Any exception

Wrap an existing exception in a TransformerException. This is used for throwing processor exceptions before the processing has started.

Constructor TransformerException(Throwable) public TransformerException(java.lang.Throwable e);

Parameters e The exception to be wrapped. Create a new TransformerException wrapping an existing exception.

Method getCause() public Throwable getCause();

85

Final 1.0.0

Package javax.xml.transform

Returns the cause of this throwable or null if the cause is nonexistent or unknown. (The cause is the throwable that caused this throwable to get thrown.)

Method getException() public Throwable getException(); See Also

javax.xml.transform.TransformerException.getCause [Method getCause()]

This method retrieves an exception that this exception wraps.

Method getLocationAsString() public String getLocationAsString(); Get the location information as a string.

Method getLocator() public SourceLocator getLocator(); Method getLocator retrieves an instance of a SourceLocator object that specifies where an error occured.

Method getMessageAndLocation() public String getMessageAndLocation(); Get the error message with location information appended.

Method initCause(Throwable) public Throwable initCause(java.lang.Throwable cause);

Parameters cause

the cause (which is saved for later retrieval by the javax.xml.transform.TransformerException.getCause [ Method getCause()] method). (A

null value is permitted, and indicates that the cause is nonexistent or unknown.) returns

a reference to this Throwable instance.

Exceptions IllegalArgumentException

if cause is this throwable. (A throwable cannot be its own cause.)

IllegalStateException

if this throwable was created with javax.xml.transform.TransformerException [ Construct  or TransformerException(java.lang.Throwable)] or javax.xml.transform.TransformerEx  ception [ Constructor TransformerException(java.lang.String, java.lang.Throwable)], or this method has already been called on this throwable.

86

Final 1.0.0

Package javax.xml.transform

Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.) This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. If this throwable was created with javax.xml.transform.TransformerException [ Constructor Transformer  Exception(java.lang.Throwable)] or javax.xml.transform.TransformerException [ Constructor TransformerExcep  tion(java.lang.String, java.lang.Throwable)], this method cannot be called even once.

Method printStackTrace() public void printStackTrace(); Print the the trace of methods from where the error originated. This will trace all nested exception objects, as well as this object.

Method printStackTrace(PrintStream) public void printStackTrace(java.io.PrintStream s);

Parameters s The stream where the dump will be sent to. Print the the trace of methods from where the error originated. This will trace all nested exception objects, as well as this object.

Method printStackTrace(PrintWriter) public void printStackTrace(java.io.PrintWriter s);

Parameters s The writer where the dump will be sent to. Print the the trace of methods from where the error originated. This will trace all nested exception objects, as well as this object.

Method setLocator(SourceLocator) public void setLocator(javax.xml.transform.SourceLocator location);

Parameters location

A SourceLocator object, or null to clear the location.

Method setLocator sets an instance of a SourceLocator object that specifies where an error occured.

Error TransformerFactoryConfigurationError Thrown when a problem with configuration with the Transformer Factories exists. This error will typically be thrown when the class of a transformation factory specified in the system properties cannot be found or instantiated.

87

Final 1.0.0

Package javax.xml.transform

Synopsis public TransformerFactoryConfigurationError extends Error { public TransformerFactoryConfigurationError(); public TransformerFactoryConfigurationError(java.lang.String msg); public TransformerFactoryConfigurationError(java.lang.Exception e); public TransformerFactoryConfigurationError(java.lang.Exception e,                                               java.lang.String msg); public String getMessage(); public Exception getException(); } Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Error | javax.xml.transform.TransformerFactoryConfigurationError

Members Constructor TransformerFactoryConfigurationError() public TransformerFactoryConfigurationError(); Create a new TransformerFactoryConfigurationError with no detail mesage.

Constructor TransformerFactoryConfigurationError(Exception) public TransformerFactoryConfigurationError(java.lang.Exception e);

Parameters e The exception to be encapsulated in a TransformerFactoryConfigurationError. Create a new TransformerFactoryConfigurationError with a given Exception base cause of the error.

Constructor TransformerFactoryConfigurationError(Exception, String) public TransformerFactoryConfigurationError(java.lang.Exception e,                                               java.lang.String msg);

88

Final 1.0.0

Package javax.xml.transform

Parameters e

The exception to be encapsulated in a TransformerFactoryConfigurationError

msg

The detail message.

Create a new TransformerFactoryConfigurationError with the given Exception base cause and detail message.

Constructor TransformerFactoryConfigurationError(String) public TransformerFactoryConfigurationError(java.lang.String msg);

Parameters msg

The error message for the exception.

Create a new TransformerFactoryConfigurationError with the String specified as an error message.

Method getException() public Exception getException(); Return the actual exception (if any) that caused this exception to be raised.

Method getMessage() public String getMessage(); Return the message (if any) for this error . If there is no message for the exception and there is an encapsulated exception then the message of that exception will be returned.

89

Final 1.0.0

Chapter 9. Package javax.xml.transform.dom This package implements DOM-specific transformation APIs. The javax.xml.transform.dom.DOMSource [ Class DOMSource] class allows the client of the implementation of this API to specify a DOM 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 [http://www.w3.org/TR/xslt#data-model] or other data models is beyond the scope of this document. Any of the nodes derived from org.w3c.dom.Node are legal input. The javax.xml.transform.dom.DOMResult [ Class DOMResult] class allows a 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 javax.xml.parsers.DocumentBuilder#newDocument to create an output org.w3c.dom.Document node. If a node is specified, it should be one of the following: org.w3c.dom.Document, org.w3c.dom.Element, or org.w3c.dom.Document  Fragment. Specification of any other node type is implementation dependent and undefined by this API. If the result is a org.w3c.dom.Document, the output of the transformation must have a single element root to set as the document element. The javax.xml.transform.dom.DOMLocator [ Interface DOMLocator] node may be passed to javax.xml.transform.Trans  formerException [ Exception TransformerException] objects, and retrieved by trying to cast the result of the javax.xml.transform.TransformerException.getLocator [ Method getLocator()] method. The implementation has no responsibility to use a DOMLocator instead of a javax.xml.transform.SourceLocator [ Interface 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.

Class DOMResult Acts as a holder for a transformation result tree in the form of a Document Object Model (DOM) tree. If no output DOM source is set, the transformation will create a Document node as the holder for the result of the transformation, which may be retrieved with javax.xml.transform.dom.DOMResult.getNode [ Method getNode()].

Synopsis public DOMResultimplements Result { public DOMResult(); public DOMResult(org.w3c.dom.Node node); public DOMResult(org.w3c.dom.Node node,                    java.lang.String systemId); public DOMResult(org.w3c.dom.Node node,                    org.w3c.dom.Node nextSibling); public DOMResult(org.w3c.dom.Node node,                    org.w3c.dom.Node nextSibling,                    java.lang.String systemId); public void setNode(org.w3c.dom.Node node); public Node getNode();

90

Final 1.0.0

Package javax.xml.transform.dom

public void setNextSibling(org.w3c.dom.Node nextSibling); public Node getNextSibling(); public void setSystemId(java.lang.String systemId); public String getSystemId(); } Author

Jeff Suttor [[email protected]]

Version

$Revision: 1.4.16.5 $, $Date: 2004/07/13 22:27:49 $

Inheritance Path java.lang.Object | javax.xml.transform.dom.DOMResult

Members Constructor DOMResult() public DOMResult(); Zero-argument default constructor. node, siblingNode and systemId will be set to null.

Constructor DOMResult(Node) public DOMResult(org.w3c.dom.Node node);

Parameters node

The DOM node that will contain the result tree.

Use a DOM node to create a new output target. In practice, the node should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragment node, or a org.w3c.dom.Element node. In other words, a node that accepts children. siblingNode and systemId will be set to null.

Constructor DOMResult(Node, Node) public DOMResult(org.w3c.dom.Node node,                    org.w3c.dom.Node nextSibling);

Parameters node

The DOM node that will contain the result tree.

91

Final 1.0.0

Package javax.xml.transform.dom

nextSibling

The child node where the result nodes should be inserted before.

Exceptions IllegalArgumentException

If nextSibling is not a sibling of node.

IllegalArgumentException

If node is null and nextSibling is not null.

Since

1.5

Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before. In practice, node and nextSibling should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragment node, or a org.w3c.dom.Element node. In other words, a node that accepts children. Use nextSibling to specify the child node where the result nodes should be inserted before. If nextSibling is not a sibling of node, then an IllegalArgumentException is thrown. If node is null and nextSibling is not null, then an IllegalArgumentException is thrown. If nextSibling is null, then the behavior is the same as calling javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node)], i.e. append the result nodes as the last child of the specified node. systemId will be set to null.

Constructor DOMResult(Node, Node, String) public DOMResult(org.w3c.dom.Node node,                    org.w3c.dom.Node nextSibling,                    java.lang.String systemId);

Parameters node

The DOM node that will contain the result tree.

nextSibling

The child node where the result nodes should be inserted before.

systemId

The system identifier which may be used in association with this node.

Exceptions IllegalArgumentException

If nextSibling is not a sibling of node.

IllegalArgumentException

If node is null and nextSibling is not null.

Since

1.5

Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before and the specified System ID. In practice, node and nextSibling should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragment node, or a org.w3c.dom.Element node. In other words, a node that accepts children. Use nextSibling to specify the child node where the result nodes should be inserted before. If nextSibling is not a sibling of node, then an IllegalArgumentException is thrown. If node is null and nextSibling is not null, then an IllegalArgumentException is thrown. If nextSibling is null, then the behavior is

92

Final 1.0.0

Package javax.xml.transform.dom

the same as calling javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, java.lang.String)], i.e. append the result nodes as the last child of the specified node and use the specified System ID.

Constructor DOMResult(Node, String) public DOMResult(org.w3c.dom.Node node,                    java.lang.String systemId);

Parameters node

The DOM node that will contain the result tree.

systemId

The system identifier which may be used in association with this node.

Use a DOM node to create a new output target with the specified System ID. In practice, the node should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragment node, or a org.w3c.dom.Element node. In other words, a node that accepts children. siblingNode will be set to null.

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the Transformer62 supports Result output of this type.

Method getNextSibling() public Node getNextSibling(); Since

1.5

Get the child node before which the result nodes will be inserted. If no node was set via javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, org.w3c.dom.Node)], javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, org.w3c.dom.Node, java.lang.String)] or javax.xml.transform.dom.DOMResult.setNextSibling [ Method setNextSib  ling(org.w3c.dom.Node)], then null will be returned.

Method getNode() public Node getNode(); Get the node that will contain the result DOM tree. If no node was set via javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node)], javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, java.lang.String)], javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, org.w3c.dom.Node)], javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, org.w3c.dom.Node, java.lang.String)] or javax.xml.transform.dom.DOMResult.setNode [ Method setNode(org.w3c.dom.Node)], then the node will be set by the transformation, and may be obtained from this method once the transformation is complete. Calling this method before the transformation will return null.

93

Final 1.0.0

Package javax.xml.transform.dom

Method getSystemId() public String getSystemId(); Get the System Identifier. If no System ID was set via javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, java.lang.String)], javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node, org.w3c.dom.Node, java.lang.String)] or javax.xml.transform.dom.DOMResult.setSystemId [ Method setSys  temId(java.lang.String)], then null will be returned.

Method setNextSibling(Node) public void setNextSibling(org.w3c.dom.Node nextSibling);

Parameters nextSibling

The child node before which the result nodes will be inserted.

Exceptions IllegalArgumentException

If nextSibling is not a descendant of node.

IllegalStateException

If node is null and nextSibling is not null.

Since

1.5

Set the child node before which the result nodes will be inserted. Use nextSibling to specify the child node before which the result nodes should be inserted. If nextSibling is not a descendant of node, then an IllegalArgumentException is thrown. If node is null and nextSibling is not null, then an IllegalStateException is thrown. If nextSibling is null, then the behavior is the same as calling javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node)], i.e. append the result nodes as the last child of the specified node.

Method setNode(Node) public void setNode(org.w3c.dom.Node node);

Parameters node

The node to which the transformation will be appended.

Exceptions IllegalStateException

If nextSibling is not null and nextSibling is not a child of node.

IllegalStateException

If node is null and nextSibling is not null.

Set the node that will contain the result DOM tree. In practice, the node should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragment node, or a org.w3c.dom.Element node. In other words, a node that accepts children.

94

Final 1.0.0

Package javax.xml.transform.dom

An IllegalStateException is thrown if nextSibling is not null and node is not a parent of nextSib  ling. An IllegalStateException is thrown if node is null and nextSibling is not null.

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URI string.

Set the systemId that may be used in association with the node.

Class DOMSource Acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree. Note that XSLT requires namespace support. Attempting to transform a DOM that was not contructed with a namespaceaware parser may result in errors. Parsers can be made namespace aware by calling javax.xml.parsers.DocumentBuild  erFactory#setNamespaceAware(boolean awareness).

Synopsis public DOMSourceimplements Source { public DOMSource(); public DOMSource(org.w3c.dom.Node n); public DOMSource(org.w3c.dom.Node node,                    java.lang.String systemID); public void setNode(org.w3c.dom.Node node); public Node getNode(); public void setSystemId(java.lang.String systemID); public String getSystemId(); } Author

Jeff Suttor [[email protected]]

Version

$Revision: 1.5.14.1.2.2 $, $Date: 2004/07/13 22:27:49 $

See Also

Document Object Model (DOM) Level 2 Specification [http://www.w3.org/TR/DOM-Level-2]

Inheritance Path java.lang.Object | javax.xml.transform.dom.DOMSource

95

Final 1.0.0

Package javax.xml.transform.dom

Members Constructor DOMSource() public DOMSource(); See Also

javax.xml.transform.Transformer.transform javax.xml.transform.Result)]

[Method

transform(javax.xml.transform.Source,

Zero-argument default constructor. If this constructor is used, and no DOM source is set using javax.xml.trans  form.dom.DOMSource.setNode [ Method setNode(org.w3c.dom.Node)] , then the Transformer62 will create an empty source org.w3c.dom.Document using javax.xml.parsers.DocumentBuilder#newDocument().

Constructor DOMSource(Node) public DOMSource(org.w3c.dom.Node n);

Parameters n The DOM node that will contain the Source tree. Create a new input source with a DOM node. The operation will be applied to the subtree rooted at this node. In XSLT, a "/" pattern still means the root of the tree (not the subtree), and the evaluation of global variables and parameters is done from the root node also.

Constructor DOMSource(Node, String) public DOMSource(org.w3c.dom.Node node,                    java.lang.String systemID);

Parameters node

The DOM node that will contain the Source tree.

systemID

Specifies the base URI associated with node.

Create a new input source with a DOM node, and with the system ID also passed in as the base URI.

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the Transformer supports Source input of this type.

Method getNode() public Node getNode(); Get the node that represents a Source DOM tree.

96

Final 1.0.0

Package javax.xml.transform.dom

Method getSystemId() public String getSystemId(); Get the base ID (URL or system ID) from where URLs will be resolved.

Method setNode(Node) public void setNode(org.w3c.dom.Node node);

Parameters node

The node that is to be transformed.

Set the node that will represents a Source DOM tree.

Method setSystemId(String) public void setSystemId(java.lang.String systemID);

Parameters systemID

Base URL for this DOM tree.

Set the base ID (URL or system ID) from where URLs will be resolved.

Interface DOMLocator Indicates the position of a node in a source DOM, intended primarily for error reporting. To use a DOMLocator, the receiver of an error must downcast the javax.xml.transform.SourceLocator [ Interface SourceLocator] object returned by an exception. A javax.xml.transform.Transformer [ Class Transformer] may use this object for purposes other than error reporting, for instance, to indicate the source node that originated a result node.

Synopsis implements public DOMLocator, SourceLocator { public Node getOriginatingNode(); } Inheritance Path javax.xml.transform.dom.DOMLocator

Members Method getOriginatingNode() public Node getOriginatingNode(); Return the node where the event occurred.

97

Final 1.0.0

Chapter 10. Package javax.xml.transform.sax This package implements SAX2-specific transformation APIs. It provides classes which allow input from 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 org.xml.sax.XMLReader, or to use a org.xml.sax.InputSource as the source. It also allows the creation of a org.xml.sax.XMLFilter, which enables transformations to "pull" from other transformations, and lets the transformer to be used polymorphically as an org.xml.sax.XMLReader. The javax.xml.transform.sax.SAXSource [ Class SAXSource] class allows the setting of an org.xml.sax.XMLReader to be used for "pulling" parse events, and an org.xml.sax.InputSource that may be used to specify the SAX source. The javax.xml.transform.sax.SAXResult [ Class SAXResult] class allows the setting of a org.xml.sax.ContentHandler to be the receiver of SAX2 events from the transformation. The javax.xml.transform.sax.SAXTransformerFactory [ Class SAXTransformerFactory] extends javax.xml.trans  form.TransformerFactory [ Class TransformerFactory] to provide factory methods for creating javax.xml.trans  form.sax.TemplatesHandler [ Interface TemplatesHandler], javax.xml.transform.sax.TransformerHandler [ Interface TransformerHandler], and org.xml.sax.XMLReader instances. To obtain a javax.xml.transform.sax.SAXTransformerFactory [ Class SAXTransformerFactory], the caller must cast the javax.xml.transform.TransformerFactory [ Class TransformerFactory] instance returned from javax.xml.trans  form.TransformerFactory.newInstance [ Method newInstance()]. The javax.xml.transform.sax.TransformerHandler [ Interface 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 org.xml.sax.ContentHandler interface, lexical events such as startCDATA and endCDATA are received through the org.xml.sax.ext.LexicalHandler interface, and events that signal the start or end of disabling output escaping are received via org.xml.sax.ContentHandler.processingInstruc  tion, with the target parameter being javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING [ Field PI_DISABLE_OUTPUT_ESCAPING] and javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING [ Field PI_ENABLE_OUTPUT_ESCAPING]. If parameters, output properties, or other features need to be set on the Trans  former handler, a javax.xml.transform.Transformer [ Class Transformer] reference will need to be obtained from javax.xml.transform.sax.TransformerHandler.getTransformer [ Method getTransformer()], and the methods invoked from that reference. The javax.xml.transform.sax.TemplatesHandler [ Interface TemplatesHandler] interface allows the creation of javax.xml.transform.Templates [ Interface Templates] objects from SAX2 parse events. Once the org.xml.sax.Con  tentHandler events are complete, the Templates object may be obtained from javax.xml.transform.sax.TemplatesHand  ler.getTemplates [ Method getTemplates()]. Note that javax.xml.transform.sax.TemplatesHandler.setSystemId [ Method setSystemId(java.lang.String)] should normally be called in order to establish a base system ID from which relative URLs may be resolved. The javax.xml.transform.sax.SAXTransformerFactory.newXMLFilter [ Method newXMLFilter(javax.xml.trans  form.Source)] method allows the creation of a 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 org.xml.sax.XMLReader, and the final transformation is caused by invoking org.xml.sax.XMLReader.parse on the final reader in the chain.

Class SAXResult Acts as an holder for a transformation Result.

98

Final 1.0.0

Package javax.xml.transform.sax

Synopsis public SAXResultimplements Result { public SAXResult(); public SAXResult(org.xml.sax.ContentHandler handler); public void setHandler(org.xml.sax.ContentHandler handler); public ContentHandler getHandler(); public void setLexicalHandler(org.xml.sax.ext.LexicalHandler handler); public LexicalHandler getLexicalHandler(); public void setSystemId(java.lang.String systemId); public String getSystemId(); } Author

Jeff Suttor [[email protected]]

Inheritance Path java.lang.Object | javax.xml.transform.sax.SAXResult

Members Constructor SAXResult() public SAXResult(); Zero-argument default constructor.

Constructor SAXResult(ContentHandler) public SAXResult(org.xml.sax.ContentHandler handler);

Parameters handler

Must be a non-null ContentHandler reference.

Create a SAXResult that targets a SAX2 org.xml.sax.ContentHandler.

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the Transformer supports Result output of this type.

99

Final 1.0.0

Package javax.xml.transform.sax

Method getHandler() public ContentHandler getHandler(); Get the org.xml.sax.ContentHandler that is the Result.

Method getLexicalHandler() public LexicalHandler getLexicalHandler(); Get a SAX2 org.xml.sax.ext.LexicalHandler for the output.

Method getSystemId() public String getSystemId(); Get the system identifier that was set with setSystemId.

Method setHandler(ContentHandler) public void setHandler(org.xml.sax.ContentHandler handler);

Parameters handler

Must be a non-null ContentHandler reference.

Set the target to be a SAX2 org.xml.sax.ContentHandler.

Method setLexicalHandler(LexicalHandler) public void setLexicalHandler(org.xml.sax.ext.LexicalHandler handler);

Parameters handler

A non-null LexicalHandler for handling lexical parse events.

Set the SAX2 org.xml.sax.ext.LexicalHandler for the output. This is needed to handle XML comments and the like. If the lexical handler is not set, an attempt should be made by the transformer to cast the org.xml.sax.ContentHandler to a LexicalHandler.

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URI string.

Method setSystemId Set the systemID that may be used in association with the org.xml.sax.ContentHandler.

100

Final 1.0.0

Package javax.xml.transform.sax

Class SAXSource Acts as an holder for SAX-style Source. Note that XSLT requires namespace support. Attempting to transform an input source that is not generated with a namespace-aware parser may result in errors. Parsers can be made namespace aware by calling the javax.xml.pars  ers.SAXParserFactory#setNamespaceAware(boolean awareness) method.

Synopsis public SAXSourceimplements Source { public SAXSource(); public SAXSource(org.xml.sax.XMLReader reader,                    org.xml.sax.InputSource inputSource); public SAXSource(org.xml.sax.InputSource inputSource); public void setXMLReader(org.xml.sax.XMLReader reader); public XMLReader getXMLReader(); public void setInputSource(org.xml.sax.InputSource inputSource); public InputSource getInputSource(); public void setSystemId(java.lang.String systemId); public String getSystemId(); static InputSource sourceToInputSource(javax.xml.transform.Source source); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.7.14.1.2.2 $, $Date: 2004/07/13 22:27:50 $

Inheritance Path java.lang.Object | javax.xml.transform.sax.SAXSource

Members Constructor SAXSource() public SAXSource(); See Also

javax.xml.transform.Transformer.transform javax.xml.transform.Result)]

101

[Method

transform(javax.xml.transform.Source,

Final 1.0.0

Package javax.xml.transform.sax

Zero-argument default constructor. If this constructor is used, and no SAX source is set using javax.xml.trans  form.sax.SAXSource.setInputSource [ Method setInputSource(org.xml.sax.InputSource)] , then the Transformer 62 will create an empty source org.xml.sax.InputSource using new InputSource().

Constructor SAXSource(InputSource) public SAXSource(org.xml.sax.InputSource inputSource);

Parameters inputSource

An input source reference that must be non-null and that will be passed to the parse method of the reader.

Create a SAXSource101, using a SAX InputSource. The javax.xml.transform.Transformer [ Class Transformer] or javax.xml.transform.sax.SAXTransformerFactory [ Class SAXTransformerFactory] creates a reader via org.xml.sax.helpers.XMLReaderFactory (if setXMLReader is not used), sets itself as the reader's org.xml.sax.Con  tentHandler, and calls reader.parse(inputSource).

Constructor SAXSource(XMLReader, InputSource) public SAXSource(org.xml.sax.XMLReader reader,                    org.xml.sax.InputSource inputSource);

Parameters reader

An XMLReader to be used for the parse.

inputSource

A SAX input source reference that must be non-null and that will be passed to the reader parse method.

Create a SAXSource101, using an org.xml.sax.XMLReader and a SAX InputSource. The javax.xml.transform.Transformer [ Class Transformer] or javax.xml.transform.sax.SAXTransformerFactory [ Class SAXTransformerFactory] will set itself to be the reader's org.xml.sax.ContentHandler, and then will call reader.parse(inputSource).

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the Transformer supports Source input of this type.

Method getInputSource() public InputSource getInputSource(); Get the SAX InputSource to be used for the Source.

Method getSystemId() public String getSystemId(); Get the base ID (URI or system ID) from where URIs will be resolved.

102

Final 1.0.0

Package javax.xml.transform.sax

Method getXMLReader() public XMLReader getXMLReader(); Get the XMLReader to be used for the Source.

Method setInputSource(InputSource) public void setInputSource(org.xml.sax.InputSource inputSource);

Parameters inputSource

A valid InputSource reference.

Set the SAX InputSource to be used for the Source.

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URI string.

Set the system identifier for this Source. If an input source has already been set, it will set the system ID or that input source, otherwise it will create a new input source. The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if no byte stream or character stream is specified).

Method setXMLReader(XMLReader) public void setXMLReader(org.xml.sax.XMLReader reader);

Parameters reader

A valid XMLReader or XMLFilter reference.

Set the XMLReader to be used for the Source.

Method sourceToInputSource(Source) static InputSource sourceToInputSource(javax.xml.transform.Source source);

Parameters source

Must be a non-null Source reference.

returns

An InputSource, or null if Source can not be converted.

Attempt to obtain a SAX InputSource object from a Source object.

103

Final 1.0.0

Package javax.xml.transform.sax

Class SAXTransformerFactory This class extends TransformerFactory to provide SAX-specific factory methods. It provides two types of ContentHand  lers, one for creating Transformers, the other for creating Templates objects. If an application wants to set the ErrorHandler or EntityResolver for an XMLReader used during a transformation, it should use a URIResolver to return the SAXSource which provides (with getXMLReader) a reference to the XMLReader.

Synopsis public SAXTransformerFactory extends TransformerFactory { protected SAXTransformerFactory(); public TransformerHandler abstract newTransformerHandler(javax.xml.transform.Source src)     throws javax.xml.transform.TransformerConfigurationException;

public TransformerHandler abstract newTransformerHandler(javax.xml.transform.Templates temp     throws javax.xml.transform.TransformerConfigurationException; public TransformerHandler abstract newTransformerHandler()     throws javax.xml.transform.TransformerConfigurationException; public TemplatesHandler abstract newTemplatesHandler()     throws javax.xml.transform.TransformerConfigurationException; public XMLFilter abstract newXMLFilter(javax.xml.transform.Source src)     throws javax.xml.transform.TransformerConfigurationException; public XMLFilter abstract newXMLFilter(javax.xml.transform.Templates templates)     throws javax.xml.transform.TransformerConfigurationException; } Inheritance Path java.lang.Object | javax.xml.transform.TransformerFactory | javax.xml.transform.sax.SAXTransformerFactory

Members Constructor SAXTransformerFactory() protected SAXTransformerFactory(); The default constructor is protected on purpose.

104

Final 1.0.0

Package javax.xml.transform.sax

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the TransformerFactory returned from javax.xml.transform.TransformerFactory.newInstance [ Method newInstance()] may be safely cast to a SAXTransformerFactory.

Field FEATURE_XMLFILTER   static java.lang.String FEATURE_XMLFILTER ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the javax.xml.transform.sax.SAXTransformerFactory.newXMLFilter [ Method newXML  Filter(javax.xml.transform.Source)] and javax.xml.transform.sax.SAXTransformerFactory.newXMLFilter [ Method newXMLFilter(javax.xml.transform.Templates)] methods are supported.

Method newTemplatesHandler() public TemplatesHandler abstract newTemplatesHandler()     throws javax.xml.transform.TransformerConfigurationException;

Exceptions TransformerConfigura  tionException

If for some reason the TemplatesHandler cannot be created.

Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.

Method newTransformerHandler() public TransformerHandler abstract newTransformerHandler()     throws javax.xml.transform.TransformerConfigurationException;

Exceptions TransformerConfigura  tionException

If for some reason the TransformerHandler cannot be created.

Get a TransformerHandler object that can process SAX ContentHandler events into a Result. The transformation is defined as an identity (or copy) transformation, for example to copy a series of SAX parse events into a DOM tree.

Method newTransformerHandler(Source) public TransformerHandler abstract newTransformerHandler(javax.xml.transform.Source src)     throws javax.xml.transform.TransformerConfigurationException;

Parameters src

The Source of the transformation instructions.

returns

TransformerHandler ready to transform SAX events.

105

Final 1.0.0

Package javax.xml.transform.sax

Exceptions TransformerConfigura  tionException

If for some reason the TransformerHandler can not be created.

Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.

Method newTransformerHandler(Templates)

public TransformerHandler abstract newTransformerHandler(javax.xml.transform.Templates temp     throws javax.xml.transform.TransformerConfigurationException;

Parameters templates

The compiled transformation instructions.

returns

TransformerHandler ready to transform SAX events.

Exceptions TransformerConfigura  tionException

If for some reason the TransformerHandler can not be created.

Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.

Method newXMLFilter(Source) public XMLFilter abstract newXMLFilter(javax.xml.transform.Source src)     throws javax.xml.transform.TransformerConfigurationException;

Parameters src

The Source of the transformation instructions.

returns

An XMLFilter object, or null if this feature is not supported.

Exceptions TransformerConfigura  tionException

If for some reason the TemplatesHandler cannot be created.

Create an XMLFilter that uses the given Source as the transformation instructions.

Method newXMLFilter(Templates) public XMLFilter abstract newXMLFilter(javax.xml.transform.Templates templates)     throws javax.xml.transform.TransformerConfigurationException;

Parameters templates

The compiled transformation instructions.

106

Final 1.0.0

Package javax.xml.transform.sax

returns

An XMLFilter object, or null if this feature is not supported.

Exceptions TransformerConfigura  tionException

If for some reason the TemplatesHandler cannot be created.

Create an XMLFilter, based on the Templates argument..

Interface TemplatesHandler A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object. Note that TemplatesHandler does not need to implement LexicalHandler.

Synopsis implements public TemplatesHandler, ContentHandler { public Templates getTemplates(); public void setSystemId(java.lang.String systemID); public String getSystemId(); } Inheritance Path javax.xml.transform.sax.TemplatesHandler

Members Method getSystemId() public String getSystemId(); Get the base ID (URI or system ID) from where relative URLs will be resolved.

Method getTemplates() public Templates getTemplates(); When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.

Method setSystemId(String) public void setSystemId(java.lang.String systemID);

107

Final 1.0.0

Package javax.xml.transform.sax

Parameters systemID

Base URI for this stylesheet.

Set the base ID (URI or system ID) for the Templates object created by this builder. This must be set in order to resolve relative URIs in the stylesheet. This must be called before the startDocument event.

Interface TransformerHandler A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Synopsis implements public TransformerHandler, ContentHandler, LexicalHandler, DTDHandler { public void setResult(javax.xml.transform.Result result)     throws java.lang.IllegalArgumentException; public void setSystemId(java.lang.String systemID); public String getSystemId(); public Transformer getTransformer(); } Inheritance Path javax.xml.transform.sax.TransformerHandler

Members Method getSystemId() public String getSystemId(); Get the base ID (URI or system ID) from where relative URLs will be resolved.

Method getTransformer() public Transformer getTransformer(); Get the Transformer62 associated with this handler, which is needed in order to set parameters and output properties.

Method setResult(Result) public void setResult(javax.xml.transform.Result result)     throws java.lang.IllegalArgumentException;

Parameters result

A Result instance, should not be null.

108

Final 1.0.0

Package javax.xml.transform.sax

Exceptions IllegalArgumentException

if result is invalid for some reason.

Set the Result associated with this TransformerHandler to be used for the transformation.

Method setSystemId(String) public void setSystemId(java.lang.String systemID);

Parameters systemID

Base URI for the source tree.

Set the base ID (URI or system ID) from where relative URLs will be resolved.

109

Final 1.0.0

C h a p t e r   1 1 .   P a c k a g e javax.xml.transform.stream This package implements stream- and URI- specific transformation APIs. The javax.xml.transform.stream.StreamSource [ Class StreamSource] class provides methods for specifying java.io.InputStream input, java.io.Reader input, and URL input in the form of strings. Even if an input stream or reader is specified as the source, javax.xml.transform.stream.StreamSource.setSystemId [ Method setSys  temId(java.lang.String)] 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 javax.xml.transform.SourceLocator [ Interface SourceLocator] information. The javax.xml.transform.stream.StreamResult [ Class StreamResult] class provides methods for specifying java.io.OutputStream, 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.

Class StreamResult Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.

Synopsis public StreamResultimplements Result { public StreamResult(); public StreamResult(java.io.OutputStream outputStream); public StreamResult(java.io.Writer writer); public StreamResult(java.lang.String systemId); public StreamResult(java.io.File f); public void setOutputStream(java.io.OutputStream outputStream); public OutputStream getOutputStream(); public void setWriter(java.io.Writer writer); public Writer getWriter(); public void setSystemId(java.lang.String systemId); public void setSystemId(java.io.File f); public String getSystemId();

110

Final 1.0.0

Package javax.xml.transform.stream

} Author

Jeff Suttor [[email protected]]

Inheritance Path java.lang.Object | javax.xml.transform.stream.StreamResult

Members Constructor StreamResult() public StreamResult(); Zero-argument default constructor.

Constructor StreamResult(File) public StreamResult(java.io.File f);

Parameters f Must a non-null File reference. Construct a StreamResult from a File.

Constructor StreamResult(OutputStream) public StreamResult(java.io.OutputStream outputStream);

Parameters outputStream

A valid OutputStream reference.

Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.

Constructor StreamResult(String) public StreamResult(java.lang.String systemId);

Parameters systemId

Must be a String that conforms to the URI syntax.

Construct a StreamResult from a URL.

Constructor StreamResult(Writer) public StreamResult(java.io.Writer writer);

111

Final 1.0.0

Package javax.xml.transform.stream

Parameters writer

A valid Writer reference.

Construct a StreamResult from a character stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding. However, there are times when it is useful to write to a character stream, such as when using a StringWriter.

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the Transformer supports Result output of this type.

Method getOutputStream() public OutputStream getOutputStream(); Get the byte stream that was set with setOutputStream.

Method getSystemId() public String getSystemId(); Get the system identifier that was set with setSystemId.

Method getWriter() public Writer getWriter(); Get the character stream that was set with setWriter.

Method setOutputStream(OutputStream) public void setOutputStream(java.io.OutputStream outputStream);

Parameters outputStream

A valid OutputStream reference.

Set the ByteStream that is to be written to. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.

Method setSystemId(File) public void setSystemId(java.io.File f);

Parameters f Must a non-null File reference. Set the system ID from a File reference.

112

Final 1.0.0

Package javax.xml.transform.stream

Note the use of java.io.File.toURI and java.io.File.toURL. toURI() is prefered and used if possible. To allow JAXP 1.3 to run on J2SE 1.3, toURL() is used if a java.lang.NoSuchMethodException is thrown by the attempt to use toURI().

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URI string.

Set the systemID that may be used in association with the byte or character stream, or, if neither is set, use this value as a writeable URI (probably a file name).

Method setWriter(Writer) public void setWriter(java.io.Writer writer);

Parameters writer

A valid Writer reference.

Set the writer that is to receive the result. Normally, a stream should be used rather than a writer, so that the transformer may use instructions contained in the transformation instructions to control the encoding. However, there are times when it is useful to write to a writer, such as when using a StringWriter.

Class StreamSource Acts as an holder for a transformation Source in the form of a stream of XML markup. Note: Due to their internal use of either a java.io.Reader or java.io.InputStream instance, StreamSource113 instances may only be used once.

Synopsis public StreamSourceimplements Source { public StreamSource(); public StreamSource(java.io.InputStream inputStream); public StreamSource(java.io.InputStream inputStream,                       java.lang.String systemId); public StreamSource(java.io.Reader reader); public StreamSource(java.io.Reader reader,                       java.lang.String systemId); public StreamSource(java.lang.String systemId); public StreamSource(java.io.File f);

113

Final 1.0.0

Package javax.xml.transform.stream

public void setInputStream(java.io.InputStream inputStream); public InputStream getInputStream(); public void setReader(java.io.Reader reader); public Reader getReader(); public void setPublicId(java.lang.String publicId); public String getPublicId(); public void setSystemId(java.lang.String systemId); public String getSystemId(); public void setSystemId(java.io.File f); } Author

Jeff Suttor [[email protected]]

Version

$Revision: 1.6.12.3 $, $Date: 2004/07/13 22:27:51 $

Inheritance Path java.lang.Object | javax.xml.transform.stream.StreamSource

Members Constructor StreamSource() public StreamSource(); See Also

javax.xml.transform.Transformer.transform javax.xml.transform.Result)]

[Method

transform(javax.xml.transform.Source,

Zero-argument default constructor. If this constructor is used, and no Stream source is set using javax.xml.trans  form.stream.StreamSource.setInputStream [ Method setInputStream(java.io.InputStream)] or javax.xml.trans  form.stream.StreamSource.setReader [ Method setReader(java.io.Reader)], then the Transformer62 will create an empty source java.io.InputStream using new InputStream().

Constructor StreamSource(File) public StreamSource(java.io.File f);

Parameters f Must a non-null File reference. Construct a StreamSource from a File.

114

Final 1.0.0

Package javax.xml.transform.stream

Constructor StreamSource(InputStream) public StreamSource(java.io.InputStream inputStream);

Parameters inputStream

A valid InputStream reference to an XML stream.

Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration. If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.

Constructor StreamSource(InputStream, String) public StreamSource(java.io.InputStream inputStream,                       java.lang.String systemId);

Parameters inputStream

A valid InputStream reference to an XML stream.

systemId

Must be a String that conforms to the URI syntax.

Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. This constructor allows the systemID to be set in addition to the input stream, which allows relative URIs to be processed.

Constructor StreamSource(Reader) public StreamSource(java.io.Reader reader);

Parameters reader

A valid Reader reference to an XML character stream.

Construct a StreamSource from a character reader. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.

Constructor StreamSource(Reader, String) public StreamSource(java.io.Reader reader,                       java.lang.String systemId);

Parameters reader

A valid Reader reference to an XML character stream.

systemId

Must be a String that conforms to the URI syntax.

115

Final 1.0.0

Package javax.xml.transform.stream

Construct a StreamSource from a character reader. Normally, a stream should be used rather than a reader, so that the XML parser may resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.

Constructor StreamSource(String) public StreamSource(java.lang.String systemId);

Parameters systemId

Must be a String that conforms to the URI syntax.

Construct a StreamSource from a URL.

Field FEATURE   static java.lang.String FEATURE ; If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passed this value as an argument, the Transformer supports Source input of this type.

Method getInputStream() public InputStream getInputStream(); Get the byte stream that was set with setByteStream.

Method getPublicId() public String getPublicId(); Get the public identifier that was set with setPublicId.

Method getReader() public Reader getReader(); Get the character stream that was set with setReader.

Method getSystemId() public String getSystemId(); Get the system identifier that was set with setSystemId.

Method setInputStream(InputStream) public void setInputStream(java.io.InputStream inputStream);

Parameters inputStream

A valid InputStream reference to an XML stream.

116

Final 1.0.0

Package javax.xml.transform.stream

Set the byte stream to be used as input. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. If this Source object is used to process a stylesheet, normally setSystemId should also be called, so that relative URL references can be resolved.

Method setPublicId(String) public void setPublicId(java.lang.String publicId);

Parameters publicId

The public identifier as a string.

Set the public identifier for this Source. The public identifier is always optional: if the application writer includes one, it will be provided as part of the location information.

Method setReader(Reader) public void setReader(java.io.Reader reader);

Parameters reader

A valid Reader reference to an XML CharacterStream.

Set the input to be a character reader. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.

Method setSystemId(File) public void setSystemId(java.io.File f);

Parameters f Must a non-null File reference. Set the system ID from a File reference.

Method setSystemId(String) public void setSystemId(java.lang.String systemId);

Parameters systemId

The system identifier as a URL string.

Set the system identifier for this Source. The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if there is no byte stream or character stream specified).

117

Final 1.0.0

Chapter 12. Package javax.xml.namespace XML Namespace processing. The following XML standards apply: •

XML Schema Part2: Datatypes specification [http://www.w3.org/TR/xmlschema-2/#QName]



Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames]



Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata]

Class QName QName118 represents a qualified name as defined in the XML specifications: XML Schema Part2: Datatypes specification [ h t t p : / / w w w. w 3 . o rg / T R / x m l s c h e m a - 2 / # Q N a m e ] , Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames], Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata]. The value of a QName118 contains a Namespace URI, local part and prefix. The prefix is included in QName118 to retain lexical information when present in an XML input source. The prefix is NOT used in QName.equals(Object) [ Method equals(java.lang.Object)] or to compute the QName.hashCode() [ Method hashCode()]. Equality and the hash code are defined using only the Namespace URI and local part. If not specified, the Namespace URI is set to XMLConstants.NULL_NS_URI. If not specified, the prefix is set to XM  LConstants.DEFAULT_NS_PREFIX. QName118 is immutable.

Synopsis public QNameimplements Serializable { public QName(java.lang.String namespaceURI,                java.lang.String localPart); public QName(java.lang.String namespaceURI,                java.lang.String localPart,                java.lang.String prefix); public QName(java.lang.String localPart); public String getNamespaceURI(); public String getLocalPart(); public String getPrefix(); final boolean equals(java.lang.Object objectToTest); final int hashCode();

118

Final 1.0.0

Package javax.xml.namespace

public String toString(); static QName valueOf(java.lang.String qNameAsString); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.10 $, $Date: 2004/02/09 23:41:21 $

Since

1.5

See Also

XML Schema Part2: Datatypes specification [http://www.w3.org/TR/xmlschema-2/#QName], Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames], Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata]

Inheritance Path java.lang.Object | javax.xml.namespace.QName

Members Constructor QName(String) public QName(java.lang.String localPart);

Parameters localPart See Also

local part of the QName118 QName(String namespaceURI, String localPart) [Constructor QName(java.lang.String, java.lang.String)], QName(String namespaceURI, String localPart, String prefix) [Constructor QName(java.lang.String, java.lang.String, java.lang.String)]

QName118 constructor specifying the local part. If the local part is null an IllegalArgumentException is thrown. A local part of "" is allowed to preserve compatible behavior with QName 1.0. When using this constructor, the Namespace URI is set to XMLConstants.NULL_NS_URI and the prefix is set to XM  LConstants.DEFAULT_NS_PREFIX. In an XML context, all Element and Attribute names exist in the context of a Namespace. Making this explicit during the construction of a QName118 helps prevent hard to diagnosis XML validity errors. The constructors QName(String namespaceURI, String localPart) [Constructor QName(java.lang.String, java.lang.String)] and javax.xml.namespace.QName [Constructor QName(java.lang.String, java.lang.String, java.lang.String)] are preferred. The local part is not validated as a NCName [http://www.w3.org/TR/REC-xml-names/#NT-NCName] as specified in Namespaces in XML [http://www.w3.org/TR/REC-xml-names/].

119

Final 1.0.0

Package javax.xml.namespace

Constructor QName(String, String) public QName(java.lang.String namespaceURI,                java.lang.String localPart);

Parameters namespaceURI

Namespace URI of the QName118

localPart

local part of the QName118

See Also

QName(String namespaceURI, String localPart, String prefix) [Constructor QName(java.lang.String, java.lang.String, java.lang.String)]

QName118 constructor specifying the Namespace URI and local part. If the Namespace URI is null, it is set to XMLConstants.NULL_NS_URI. This value represents no explicitly defined Namespace as defined by the Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames] specific  ation. This action preserves compatible behavior with QName 1.0. Explicitly providing the XMLCon  stants.NULL_NS_URI value is the preferred coding style. If the local part is null an IllegalArgumentException is thrown. A local part of "" is allowed to preserve compatible behavior with QName 1.0. When using this constructor, the prefix is set to XMLConstants.DEFAULT_NS_PREFIX. The Namespace URI is not validated as a URI reference [http://www.ietf.org/rfc/rfc2396.txt]. The local part is not validated as a NCName [http://www.w3.org/TR/REC-xml-names/#NT-NCName] as specified in Namespaces in XML [http://www.w3.org/TR/REC-xml-names/].

Constructor QName(String, String, String) public QName(java.lang.String namespaceURI,                java.lang.String localPart,                java.lang.String prefix);

Parameters namespaceURI

Namespace URI of the QName118

localPart

local part of the QName118

prefix

prefix of the QName118

QName118 constructor specifying the Namespace URI, local part and prefix. If the Namespace URI is null, it is set to XMLConstants.NULL_NS_URI. This value represents no explicitly defined Namespace as defined by the Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames] specific  ation. This action preserves compatible behavior with QName 1.0. Explicitly providing the XMLCon  stants.NULL_NS_URI value is the preferred coding style. If the local part is null an IllegalArgumentException is thrown. A local part of "" is allowed to preserve compatible behavior with QName 1.0.

120

Final 1.0.0

Package javax.xml.namespace

If the prefix is null, an IllegalArgumentException is thrown. Use XMLConstants.DEFAULT_NS_PREFIX to explicitly indicate that no prefix is present or the prefix is not relevant. The Namespace URI is not validated as a URI reference [http://www.ietf.org/rfc/rfc2396.txt]. The local part and prefix are not validated as a NCName [http://www.w3.org/TR/REC-xml-names/#NT-NCName] as specified in Namespaces in XML [http://www.w3.org/TR/REC-xml-names/].

Method equals(Object) final boolean equals(java.lang.Object objectToTest);

Parameters objectToTest

the Object to test for equality with this QName118

returns

true if the given Object is equal to this QName118 else false

Test this QName118 for equality with another Object. If the Object to be tested is not a QName118 or is null, then this method returns false. Two QName118s are considered equal if and only if both the Namespace URI and local part are equal. This method uses String.equals() to check equality of the Namespace URI and local part. The prefix is NOT used to determine equality. This method satisfies the general contract of Object.equals(Object)

Method getLocalPart() public String getLocalPart(); Get the local part of this QName118.

Method getNamespaceURI() public String getNamespaceURI(); Get the Namespace URI of this QName118.

Method getPrefix() public String getPrefix(); Get the prefix of this QName118. The prefix assigned to a QName118 might NOT be valid in a different context. For example, a QName118 may be assigned a prefix in the context of parsing a document but that prefix may be invalid in the context of a different document.

Method hashCode() final int hashCode(); Generate the hash code for this QName118.

121

Final 1.0.0

Package javax.xml.namespace

The hash code is calculated using both the Namespace URI and the local part of the QName118. The prefix is NOT used to calculate the hash code. This method satisfies the general contract of Object.hashCode().

Method toString() public String toString(); String representation of this QName118. The commonly accepted way of representing a QName118 as a String was defined [http://jclark.com/xml/xmlns.htm] by James Clark. Although this is not a standard specification, it is in common use, e.g. javax.xml.transform.Trans  former#setParameter(String name, Object value). This implementation represents a QName118 as: "{" + Namespace URI + "}" + local part. If the Namespace URI .equals(XMLConstants.NULL_NS_URI), only the local part is returned. An appropriate use of this method is for debugging or logging for human consumption. Note the prefix value is NOT returned as part of the String representation. This method satisfies the general contract of Object.toString().

Method valueOf(String) static QName valueOf(java.lang.String qNameAsString);

Parameters qNameAsString

String representation of the QName118

returns

QName118 corresponding to the given String

See Also

QName.toString() [Method toString()]

QName118 derived from parsing the formatted String. If the String is null or does not conform to QName.toString() [ Method toString()] formatting, an IllegalAr  gumentException is thrown. The StringMUST be in the form returned by QName.toString() [Method toString()]. The commonly accepted way of representing a QName118 as a String was defined [http://jclark.com/xml/xmlns.htm] by James Clark. Although this is not a standard specification, it is in common use, e.g. javax.xml.transform.Trans  former#setParameter(String name, Object value). This implementation parses a String formatted as: "{" + Namespace URI + "}" + local part. If the Namespace URI .equals(XMLConstants.NULL_NS_URI), only the local part should be provided. The prefix value CANNOT be represented in the String and will be set to XMLConstants.DEFAULT_NS_PREFIX. This method does not do full validation of the resulting QName118. The Namespace URI is not validated as a URI reference [http://www.ietf.org/rfc/rfc2396.txt]. The local part is not validated as a NCName [http://www.w3.org/TR/REC-xml-names/#NT-NCName] as specified in Namespaces in XML [http://www.w3.org/TR/REC-xml-names/].

122

Final 1.0.0

Package javax.xml.namespace

Interface NamespaceContext Interface for read only XML Namespace context processing. An XML Namespace has the properties: •

Namespace URI: Namespace name expressed as a URI to which the prefix is bound



prefix: syntactically, this is the part of the attribute name following the XMLConstants.XMLNS_ATTRIBUTE ("xmlns") in the Namespace declaration

example: All get*(*) methods operate in the current scope for Namespace URI and prefix resolution. Note that a Namespace URI can be bound to multiple prefixes in the current scope. This can occur when multiple XM  LConstants.XMLNS_ATTRIBUTE ("xmlns") Namespace declarations occur in the same Start-Tag and refer to the same Namespace URI. e.g.



This can also occur when the same Namespace URI is used in multiple XMLConstants.XMLNS_ATTRIBUTE ("xmlns") Namespace declarations in the logical parent element hierarchy. e.g.

...

A prefix can only be bound to a single Namespace URI in the current scope.

Synopsis implements public NamespaceContext { public String getNamespaceURI(java.lang.String prefix); public String getPrefix(java.lang.String namespaceURI); public Iterator getPrefixes(java.lang.String namespaceURI); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.4.16.1 $, $Date: 2004/06/28 18:20:38 $

123

Final 1.0.0

Package javax.xml.namespace

Since

1.5

See Also

javax.XMLConstants for declarations of common XML values, XML Schema Part2: Datatypes [http://www.w3.org/TR/xmlschema-2/#QName], Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames], Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata]

Inheritance Path javax.xml.namespace.NamespaceContext

Members Method getNamespaceURI(String) public String getNamespaceURI(java.lang.String prefix);

Parameters prefix

prefix to look up

returns

Namespace URI bound to prefix in the current scope

Get Namespace URI bound to a prefix in the current scope. When requesting a Namespace URI by prefix, the following table describes the returned Namespace URI value for all possible prefix values: getNamespaceURI(prefix) return value for specified prefixes prefix parameter

Namespace URI return value

DEFAULT_NS_PREFIX ("")

default Namespace URI in the current scope or XMLCon  stants.NULL_NS_URI("") when there is no default Namespace URI in the current scope

bound prefix

Namespace URI bound to prefix in current scope

unbound prefix

XMLConstants.NULL_NS_URI("")

XMLConstants.XML_NS_PREFIX ("xml")

XMLConstants.XML_NS_URI tp://www.w3.org/XML/1998/namespace")

XMLConstants.XMLNS_ATTRIBUTE ("xmlns")

XMLConstants.XMLNS_ATTRIBUTE_NS_URI ("ht  tp://www.w3.org/2000/xmlns/")

null

IllegalArgumentException is thrown

Method getPrefix(String) public String getPrefix(java.lang.String namespaceURI);

Parameters namespaceURI

URI of Namespace to lookup

returns

prefix bound to Namespace URI in current context

124

Final 1.0.0

("ht 

Package javax.xml.namespace

Get prefix bound to Namespace URI in the current scope. To get all prefixes bound to a Namespace URI in the current scope, use javax.xml.namespace.NamespaceContext.get  Prefixes [ Method getPrefixes(java.lang.String)]. When requesting a prefix by Namespace URI, the following table describes the returned prefix value for all Namespace URI values: getPrefix(namespaceURI) return value for specified Namespace URIs Namespace URI parameter

prefix value returned



XMLConstants.DEFAULT_NS_PREFIX ("")

bound Namespace URI

prefix bound to Namespace URI in the current scope, if multiple prefixes are bound to the Namespace URI in the current scope, a single arbitrary prefix, whose choice is implementation dependent, is returned

unbound Namespace URI

null

XMLConstants.XML_NS_URI tp://www.w3.org/XML/1998/namespace")

("ht  XMLConstants.XML_NS_PREFIX ("xml")

XMLConstants.XMLNS_ATTRIBUTE_NS_URI ("ht  XMLConstants.XMLNS_ATTRIBUTE ("xmlns") tp://www.w3.org/2000/xmlns/") IllegalArgumentException is thrown

null

Method getPrefixes(String) public Iterator getPrefixes(java.lang.String namespaceURI);

Parameters namespaceURI

URI of Namespace to lookup

returns

Iterator for all prefixes bound to the Namespace URI in the current scope

Get all prefixes bound to a Namespace URI in the current scope. An Iterator over String elements is returned in an arbitrary, implementation dependent, order. The Iterator is not modifiable. e.g. the remove() method will throw UnsupportedOperationException. When requesting prefixes by Namespace URI, the following table describes the returned prefixes value for all Namespace URI values: getPrefixes(namespaceURI) return value for specified Namespace URIs Namespace URI parameter

prefixes value returned

bound Namespace URI, including the current scope in an arbitrary, implementation dependent, order unbound Namespace URI

empty Iterator

XMLConstants.XML_NS_URI tp://www.w3.org/XML/1998/namespace")

125

("ht  Iterator with one element set to XMLCon  stants.XML_NS_PREFIX ("xml")

Final 1.0.0

Package javax.xml.namespace

getPrefixes(namespaceURI) return value for specified Namespace URIs Namespace URI parameter

prefixes value returned

XMLConstants.XMLNS_ATTRIBUTE_NS_URI ("ht  Iterator with one element set to XMLConstants.XM  tp://www.w3.org/2000/xmlns/") LNS_ATTRIBUTE ("xmlns") IllegalArgumentException is thrown

null

126

Final 1.0.0

Chapter 13. Package 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: •

XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath]

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 element in an XML document such as the following:

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 elements in the following document would be selected by the /foo/bar expression:

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

127

Final 1.0.0

Package javax.xml.xpath

//bar A wildcard operator, *, causes all element nodes to be selected. The following example selects all children elements of a 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 element

/foo/bar/text()

Selects the text nodes of the element. No distinction is made between escaped and non-escaped character data.

/foo/bar/comment()

Selects all comment nodes contained in the ele  ment.

/foo/bar/processing-instruction()

Selects all processing-instruction nodes contained in the element.

Predicates allow for refining the nodes selected by an XPath location path. Predicates are of the form [expression]. The following example selects all 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"); NodeSet nodes = (NodeSet) 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

128

Final 1.0.0

Package javax.xml.xpath



Number



String

The desired return type is specified by a 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.evalu  ate(...) convenience methods. The allowed QName values are specified as constants in the javax.xml.xpath.XPathConstants [ Class XPathConstants] class; they are: •

javax.xml.xpath.XPathConstants.NODESET [ Field NODESET]



javax.xml.xpath.XPathConstants.NODE [ Field NODE]



javax.xml.xpath.XPathConstants.STRING [ Field STRING]



javax.xml.xpath.XPathConstants.BOOLEAN [ Field BOOLEAN]



javax.xml.xpath.XPathConstants.NUMBER [ Field 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 fol  lowing XML document:

The 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 element, a relative XPath expression can now written to select the child element:

129

Final 1.0.0

Package javax.xml.xpath

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

Author Ben Galbraith [mailto:[email protected]]



Author Norman Walsh [mailto:[email protected]]



Author Jeff Suttor [mailto:[email protected]]



See XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath]



Since 1.5

Class XPathConstants XPath constants.

Synopsis public XPathConstants { } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.7.16.1 $, $Date: 2004/05/26 22:31:04 $

Since

1.5

See Also

XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath]

Inheritance Path java.lang.Object | javax.xml.xpath.XPathConstants

Members Field BOOLEAN   static javax.xml.namespace.QName BOOLEAN ; The XPath 1.0 boolean data type. Maps to Java java.lang.Boolean.

Field DOM_OBJECT_MODEL   static java.lang.String DOM_OBJECT_MODEL ;

130

Final 1.0.0

Package javax.xml.xpath

The URI for the DOM object model, "http://java.sun.com/jaxp/xpath/dom".

Field NODE   static javax.xml.namespace.QName NODE ; The XPath 1.0 NodeSet data type. Maps to Java org.w3c.dom.Node.

Field NODESET   static javax.xml.namespace.QName NODESET ; The XPath 1.0 NodeSet data type. Maps to Java org.w3c.dom.NodeList.

Field NUMBER   static javax.xml.namespace.QName NUMBER ; The XPath 1.0 number data type. Maps to Java java.lang.Double.

Field STRING   static javax.xml.namespace.QName STRING ; The XPath 1.0 string data type. Maps to Java java.lang.String.

Class XPathFactory An XPathFactory131 instance can be used to create javax.xml.xpath.XPath [ Interface XPath] objects. See javax.xml.xpath.XPathFactory.newInstance [ Method newInstance(java.lang.String)] for lookup mechanism.

Synopsis public XPathFactory { protected XPathFactory(); static XPathFactory newInstance(); static XPathFactory newInstance(java.lang.String uri)     throws XPathFactoryConfigurationException; public boolean abstract isObjectModelSupported(java.lang.String objectModel);

131

Final 1.0.0

Package javax.xml.xpath

public void abstract setFeature(java.lang.String name,                                   boolean value)     throws XPathFactoryConfigurationException; public boolean abstract getFeature(java.lang.String name)     throws XPathFactoryConfigurationException;

public void abstract setXPathVariableResolver(javax.xml.xpath.XPathVariableResolver resolve

public void abstract setXPathFunctionResolver(javax.xml.xpath.XPathFunctionResolver resolve public XPath abstract newXPath(); } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.13.10.1 $, $Date: 2004/05/07 00:34:05 $

Since

1.5

Inheritance Path java.lang.Object | javax.xml.xpath.XPathFactory

Members Constructor XPathFactory() protected XPathFactory(); Protected constructor as javax.xml.xpath.XPathFactory.newInstance [ Method newInstance()] or javax.xml.xpath.XPathFactory.newInstance [ Method newInstance(java.lang.String)] should be used to create a new instance of an XPathFactory131.

Field DEFAULT_OBJECT_MODEL_URI   static java.lang.String DEFAULT_OBJECT_MODEL_URI ; Default Object Model URI.

Field DEFAULT_PROPERTY_NAME   static java.lang.String DEFAULT_PROPERTY_NAME ; The default property name according to the JAXP spec.

Method getFeature(String) public boolean abstract getFeature(java.lang.String name)     throws XPathFactoryConfigurationException;

132

Final 1.0.0

Package javax.xml.xpath

Parameters name

Feature name.

returns

State of the named feature.

Exceptions XPathFactoryConfigura  tionException

if this XPathFactory131 or the XPaths it creates cannot support this feature.

NullPointerException

if name is null.

Get the state of the named feature. Feature names are fully qualified java.net.URIs. Implementations may define their own features. An javax.xml.xpath.XPathFactoryConfigurationException [ Exception XPathFactoryConfigurationException] is thrown if this XPathFactory131 or the XPaths it creates cannot support the feature. It is possible for an XPathFactory 131 to expose a feature value but be unable to change its state.

Method isObjectModelSupported(String) public boolean abstract isObjectModelSupported(java.lang.String objectModel);

Parameters objectModel

Specifies the object model which the returned XPathFactory131 will understand.

returns

true if XPathFactory131 supports objectModel, else false.

Exceptions NullPointerException

If objectModel is null.

IllegalArgumentException

If objectModel.length() == 0.

Is specified object model supported by this XPathFactory131?

Method newInstance() static XPathFactory newInstance(); Get a new XPathFactory131 instance using the default object model, javax.xml.xpath.XPathFactory.DEFAULT_OB  JECT_MODEL_URI [ Field DEFAULT_OBJECT_MODEL_URI], the W3C DOM. This method is functionally equivalent to:

newInstance(DEFAULT_OBJECT_MODEL_URI)

Since the implementation for the W3C DOM is always available, this method will never fail.

133

Final 1.0.0

Package javax.xml.xpath

Method newInstance(String) static XPathFactory newInstance(java.lang.String uri)     throws XPathFactoryConfigurationException;

Parameters uri

Identifies the underlying object model. The specification only defines the URI javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI [ Field DEFAULT_OB  JECT_MODEL_URI], http://java.sun.com/jaxp/xpath/dom for the W3C DOM, the org.w3c.dom package, and implementations are free to introduce other URIs for other object models.

returns

Instance of an XPathFactory131.

Exceptions XPathFactoryConfigura  tionException

If the specified object model is unavailable.

NullPointerException

If uri is null.

IllegalArgumentException

If uri.length() == 0.

Get a new XPathFactory131 instance using the specified object model. To find a XPathFactory131 object, this method looks the following places in the following order where "the class loader" refers to the context class loader: 1.

If the system property javax.xml.xpath.XPathFactory.DEFAULT_PROPERTY_NAME [ Field DEFAULT_PROP  ERTY_NAME] + ":uri" is present, where uri is the parameter to this method, then its value is read as a class name. The method will try to create a new instance of this class by using the class loader, and returns it if it is successfully created.

2.

${java.home}/lib/jaxp.properties is read and the value associated with the key being the system property above is looked for. If present, the value is processed just like above.

3.

The class loader is asked for service provider provider-configuration files matching javax.xml.xpath.XPathFactory in the resource directory META-INF/services. See the JAR File Spe  cification for file format and parsing rules. Each potential service provider is required to implement the method:

javax.xml.xpath.XPathFactory.isObjectModelSupported [ Method isObjectModelSupported(java.lang.String)]

The first service provider found in class loader order that supports the specified object model is returned. 4.

Platform default XPathFactory131 is located in a platform specific way. There must be a platform default XPathFactory for the W3C DOM, i.e. javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI [ Field DEFAULT_OBJECT_MODEL_URI].

If everything fails, an XPathFactoryConfigurationException will be thrown. Tip for Trouble-shooting:

134

Final 1.0.0

Package javax.xml.xpath

See java.util.Properties.load for exactly how a property file is parsed. In particular, colons ':' need to be escaped in a property file, so make sure the URIs are properly escaped in it. For example:

http\://java.sun.com/jaxp/xpath/dom=org.acme.DomXPathFactory

Method newXPath() public XPath abstract newXPath(); Return a new XPath using the underlying object model determined when the XPathFactory131 was instantiated.

Method setFeature(String, boolean) public void abstract setFeature(java.lang.String name,                                   boolean value)     throws XPathFactoryConfigurationException;

Parameters name

Feature name.

value

Is feature state true or false.

Exceptions XPathFactoryConfigura  tionException

if this XPathFactory131 or the XPaths it creates cannot support this feature.

NullPointerException

if name is null.

Set a feature for this XPathFactory131 and XPaths created by this factory. Feature names are fully qualified java.net.URIs. Implementations may define their own features. An javax.xml.xpath.XPathFactoryConfigurationException [ Exception XPathFactoryConfigurationException] is thrown if this XPathFactory131 or the XPaths it creates cannot support the feature. It is possible for an XPathFactory 131 to expose a feature value but be unable to change its state. All implementations are required to support the javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING feature. When the feature is true, any reference to an external function is an error. Under these conditions, the implementation must not call the javax.xml.xpath.XPathFunctionResolver [ Interface XPathFunctionResolver] and must throw an javax.xml.xpath.XPathFunctionException [ Exception XPathFunctionException].

Method setXPathFunctionResolver(XPathFunctionResolver)

public void abstract setXPathFunctionResolver(javax.xml.xpath.XPathFunctionResolver resolve

Parameters resolver

XPath function resolver.

135

Final 1.0.0

Package javax.xml.xpath

Exceptions NullPointerException

If resolver is null.

Establish a default function resolver. Any XPath objects constructed from this factory will use the specified resolver by default. A NullPointerException is thrown if resolver is null.

Method setXPathVariableResolver(XPathVariableResolver)

public void abstract setXPathVariableResolver(javax.xml.xpath.XPathVariableResolver resolve

Parameters resolver

Variable resolver.

Exceptions NullPointerException

If resolver is null.

Establish a default variable resolver. Any XPath objects constructed from this factory will use the specified resolver by default. A NullPointerException is thrown if resolver is null.

Interface XPath XPath provides access to the XPath evaluation environment and expressions. Evaluation of XPath Expressions. context

If a request is made to evaluate the expression in the ab  sence of a context item, an empty document node will be used for the context. For the purposes of evaluating XPath expressions, a DocumentFragment is treated like a Docu  ment node.

variables

If the expression contains a variable reference, its value will be found through the javax.xml.xpath.XPathVari  ableResolver [Interface XPathVariableResolver] set with javax.xml.xpath.XPath.setXPathVariableResolver [Method setXPathVariableResolver(javax.xml.xpath.XPathVari  ableResolver)]. An javax.xml.xpath.XPathExpressionEx  ception [Exception XPathExpressionException] is raised if the variable resolver is undefined or the resolver returns null for the variable. The value of a variable must be immutable through the course of any single evaluation.

functions

If the expression contains a function reference, the function will be found through the javax.xml.xpath.XPathFunction  Resolver [Interface XPathFunctionResolver] set with javax.xml.xpath.XPath.setXPathFunctionResolver

136

Final 1.0.0

Package javax.xml.xpath

Evaluation of XPath Expressions. [Method s e t X Pa t h F u n c t i o n R e s o l v   er(javax.xml.xpath.XPathFunctionResolver)]. An javax.xml.xpath.XPathExpressionException [Exception XPathExpressionException] is raised if the function resolv  er is undefined or the function resolver returns null for the function. QNames

QNames in the expression are resolved against the XPath namespace context set with javax.xml.xpath.XPath.set  NamespaceContext [Method setNamespaceCon  text(javax.xml.namespace.NamespaceContext)].

result

This result of evaluating an expression is converted to an instance of the desired return type. Valid return types are defined in javax.xml.xpath.XPathConstants [Class XPathConstants]. Conversion to the return type follows XPath conversion rules.

Synopsis implements public XPath { public void reset(); public void setXPathVariableResolver(javax.xml.xpath.XPathVariableResolver resolver); public XPathVariableResolver getXPathVariableResolver(); public void setXPathFunctionResolver(javax.xml.xpath.XPathFunctionResolver resolver); public XPathFunctionResolver getXPathFunctionResolver(); public void setNamespaceContext(javax.xml.namespace.NamespaceContext nsContext); public NamespaceContext getNamespaceContext(); public XPathExpression compile(java.lang.String expression)     throws XPathExpressionException; public Object evaluate(java.lang.String expression,                          java.lang.Object item,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException; public String evaluate(java.lang.String expression,                          java.lang.Object item)     throws XPathExpressionException; public Object evaluate(java.lang.String expression,                          org.xml.sax.InputSource source,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException;

137

Final 1.0.0

Package javax.xml.xpath

public String evaluate(java.lang.String expression,                          org.xml.sax.InputSource source)     throws XPathExpressionException; } Author

Norman Walsh [[email protected]], Jeff Suttor [[email protected]]

Version

$Revision: 1.12.14.2.2.3 $, $Date: 2004/07/01 17:49:22 $

Since

1.5

See Also

XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath]

Inheritance Path javax.xml.xpath.XPath

Members Method compile(String) public XPathExpression compile(java.lang.String expression)     throws XPathExpressionException;

Parameters expression

The XPath expression.

returns

Compiled XPath expression.

Exceptions XPathExpressionExcep  tion

If expression cannot be compiled.

NullPointerException

If expression is null.

Compile an XPath expression for later evaluation. If expression contains any javax.xml.xpath.XPathFunction [ Interface XPathFunction]s, they must be available via the javax.xml.xpath.XPathFunctionResolver [ Interface XPathFunctionResolver]. An javax.xml.xpath.XPathEx  pressionException [ Exception XPathExpressionException] will be thrown if the XPathFunction cannot be resovled with the XPathFunctionResolver. If expression is null, a NullPointerException is thrown.

Method evaluate(String, InputSource) public String evaluate(java.lang.String expression,                          org.xml.sax.InputSource source)     throws XPathExpressionException;

138

Final 1.0.0

Package javax.xml.xpath

Parameters expression

The XPath expression.

source

The InputSource of the document to evaluate over.

returns

The String that is the result of evaluating the expression and converting the result to a String.

Exceptions XPathExpressionExcep  tion

If expression cannot be evaluated.

NullPointerException

If expression or source is null.

Evaluate an XPath expression in the context of the specified InputSource and return the result as a String. This method calls javax.xml.xpath.XPath.evaluate [ Method evaluate(java.lang.String, org.xml.sax.InputSource, javax.xml.namespace.QName)] with a returnType of javax.xml.xpath.XPathConstants.STRING [ Field STRING]. See Evaluation of XPath Expressions [#XPath-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If expression or source is null, then a NullPointerException is thrown.

Method evaluate(String, InputSource, QName) public Object evaluate(java.lang.String expression,                          org.xml.sax.InputSource source,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException;

Parameters expression

The XPath expression.

source

The input source of the document to evaluate over.

returnType

The desired return type.

returns

The Object that encapsulates the result of evaluating the expression.

Exceptions XPathExpressionExcep  tion

If expression cannot be evaluated.

IllegalArgumentException

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants].

NullPointerException

If expression, source or returnType is null.

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

139

Final 1.0.0

Package javax.xml.xpath

This method builds a data model for the org.xml.sax.InputSource and calls javax.xml.xpath.XPath.evaluate [ Method evaluate(java.lang.String, java.lang.Object, javax.xml.namespace.QName)] on the resulting document object. See Evaluation of XPath Expressions [#XPath-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants], then an IllegalArgumentException is thrown. If expression, source or returnType is null, then a NullPointerException is thrown.

Method evaluate(String, Object) public String evaluate(java.lang.String expression,                          java.lang.Object item)     throws XPathExpressionException;

Parameters expression

The XPath expression.

item

The starting context (node or node list, for example).

returns

The String that is the result of evaluating the expression and converting the result to a String.

Exceptions XPathExpressionExcep  tion

If expression cannot be evaluated.

NullPointerException

If expression is null.

Evaluate an XPath expression in the specified context and return the result as a String. This method calls javax.xml.xpath.XPath.evaluate [ Method evaluate(java.lang.String, java.lang.Object, javax.xml.namespace.QName)] with a returnType of javax.xml.xpath.XPathConstants.STRING [ Field STRING]. See Evaluation of XPath Expressions [#XPath-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If a null value is provided for item, an empty document will be used for the context. If expression is null, then a NullPointerException is thrown.

Method evaluate(String, Object, QName) public Object evaluate(java.lang.String expression,                          java.lang.Object item,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException;

Parameters expression

The XPath expression.

140

Final 1.0.0

Package javax.xml.xpath

item

The starting context (node or node list, for example).

returnType

The desired return type.

returns

Result of evaluating an XPath expression as an Object of returnType.

Exceptions XPathExpressionExcep  tion

If expression cannot be evaluated.

IllegalArgumentException

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants].

NullPointerException

If expression or returnType is null.

Evaluate an XPath expression in the specified context and return the result as the specified type. See Evaluation of XPath Expressions [#XPath-evaluation] for context item evaluation, variable, function and QName 118 resolution and return type conversion. If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants] ( NUMBER [ Field NUMBER], STRING [ Field STRING], BOOLEAN [ Field BOOLEAN], NODE [ Field NODE] or NODESET [ Field NODESET]) then an IllegalArgumentException is thrown. If a null value is provided for item, an empty document will be used for the context. If expression or return  Type is null, then a NullPointerException is thrown.

Method getNamespaceContext() public NamespaceContext getNamespaceContext(); Return the current namespace context. null is returned in no namespace context is in effect.

Method getXPathFunctionResolver() public XPathFunctionResolver getXPathFunctionResolver(); Return the current function resolver. null is returned in no function resolver is in effect.

Method getXPathVariableResolver() public XPathVariableResolver getXPathVariableResolver(); Return the current variable resolver. null is returned in no variable resolver is in effect.

Method reset() public void reset();

141

Final 1.0.0

Package javax.xml.xpath

Reset this XPath to its original configuration. XPath is reset to the same state as when it was created with javax.xml.xpath.XPathFactory.newXPath [ Method newXPath()]. reset() is designed to allow the reuse of existing XPaths thus saving resources associated with the creation of new XPaths. The reset XPath is not guaranteed to have the same javax.xml.xpath.XPathFunctionResolver [ Interface XPathFunc  tionResolver], javax.xml.xpath.XPathVariableResolver [ Interface XPathVariableResolver] or javax.xml.namespace.NamespaceContext Objects, e.g. java.lang.Object.equals. It is guaranteed to have a functionally equal XPathFunctionResolver, XPathVariableResolver and NamespaceContext.

Method setNamespaceContext(NamespaceContext) public void setNamespaceContext(javax.xml.namespace.NamespaceContext nsContext);

Parameters nsContext

Namespace context to use.

Exceptions NullPointerException

If nsContext is null.

Establish a namespace context. A NullPointerException is thrown if nsContext is null.

Method setXPathFunctionResolver(XPathFunctionResolver) public void setXPathFunctionResolver(javax.xml.xpath.XPathFunctionResolver resolver);

Parameters resolver

XPath function resolver.

Exceptions NullPointerException

If resolver is null.

Establish a function resolver. A NullPointerException is thrown if resolver is null.

Method setXPathVariableResolver(XPathVariableResolver) public void setXPathVariableResolver(javax.xml.xpath.XPathVariableResolver resolver);

Parameters resolver

Variable resolver.

Exceptions NullPointerException

If resolver is null.

142

Final 1.0.0

Package javax.xml.xpath

Establish a variable resolver. A NullPointerException is thrown if resolver is null.

Interface XPathExpression XPathExpression provides access to compiled XPath expressions. Evaluation of XPath Expressions. context

If a request is made to evaluate the expression in the ab  sence of a context item, an empty document node will be used for the context. For the purposes of evaluating XPath expressions, a DocumentFragment is treated like a Docu  ment node.

variables

If the expression contains a variable reference, its value will be found through the javax.xml.xpath.XPathVari  ableResolver [Interface XPathVariableResolver]. An javax.xml.xpath.XPathExpressionException [Exception XPathExpressionException] is raised if the variable resolv  er is undefined or the resolver returns null for the vari  able. The value of a variable must be immutable through the course of any single evaluation.

functions

If the expression contains a function reference, the function will be found through the javax.xml.xpath.XPathFunction  Resolver [Interface XPathFunctionResolver]. An javax.xml.xpath.XPathExpressionException [Exception XPathExpressionException] is raised if the function resolv  er is undefined or the function resolver returns null for the function.

QNames

QNames in the expression are resolved against the XPath namespace context.

result

This result of evaluating an expression is converted to an instance of the desired return type. Valid return types are defined in javax.xml.xpath.XPathConstants [Class XPathConstants]. Conversion to the return type follows XPath conversion rules.

Synopsis implements public XPathExpression { public Object evaluate(java.lang.Object item,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException; public String evaluate(java.lang.Object item)     throws XPathExpressionException; public Object evaluate(org.xml.sax.InputSource source,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException;

143

Final 1.0.0

Package javax.xml.xpath

public String evaluate(org.xml.sax.InputSource source)     throws XPathExpressionException; } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.10.16.1 $, $Date: 2004/07/01 17:49:23 $

Since

1.5

See Also

XML Path Language (XPath) [http://www.w3.org/TR/xpath#section-Expressions]

Ve r s i o n

1.0,

Expressions

Inheritance Path javax.xml.xpath.XPathExpression

Members Method evaluate(InputSource) public String evaluate(org.xml.sax.InputSource source)     throws XPathExpressionException;

Parameters source

The InputSource of the document to evaluate over.

returns

The String that is the result of evaluating the expression and converting the result to a String.

Exceptions XPathExpressionExcep  tion

If the expression cannot be evaluated.

NullPointerException

If source is null.

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as a String. This method calls javax.xml.xpath.XPathExpression.evaluate [ Method evaluate(org.xml.sax.InputSource, javax.xml.namespace.QName)] with a returnType of javax.xml.xpath.XPathConstants.STRING [ Field STRING]. See Evaluation of XPath Expressions [#XPathExpression-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If source is null, then a NullPointerException is thrown.

Method evaluate(InputSource, QName) public Object evaluate(org.xml.sax.InputSource source,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException;

144

Final 1.0.0

Package javax.xml.xpath

Parameters source

The InputSource of the document to evaluate over.

returnType

The desired return type.

returns

The Object that is the result of evaluating the expression and converting the result to re  turnType.

Exceptions XPathExpressionExcep  tion

If the expression cannot be evaluated.

IllegalArgumentException

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants].

NullPointerException

If source or returnType is null.

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type. This method builds a data model for the org.xml.sax.InputSource and calls javax.xml.xpath.XPathExpression.evaluate [ Method evaluate(java.lang.Object, javax.xml.namespace.QName)] on the resulting document object. See Evaluation of XPath Expressions [#XPathExpression-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants], then an IllegalArgumentException is thrown. If source or returnType is null, then a NullPointerException is thrown.

Method evaluate(Object) public String evaluate(java.lang.Object item)     throws XPathExpressionException;

Parameters item

The starting context (node or node list, for example).

returns

The String that is the result of evaluating the expression and converting the result to a String.

Exceptions XPathExpressionExcep  tion

If the expression cannot be evaluated.

Evaluate the compiled XPath expression in the specified context and return the result as a String. This method calls javax.xml.xpath.XPathExpression.evaluate [ Method evaluate(java.lang.Object, javax.xml.namespace.QName)] with a returnType of javax.xml.xpath.XPathConstants.STRING [ Field STRING].

145

Final 1.0.0

Package javax.xml.xpath

See Evaluation of XPath Expressions [#XPathExpression-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If a null value is provided for item, an empty document will be used for the context.

Method evaluate(Object, QName) public Object evaluate(java.lang.Object item,                          javax.xml.namespace.QName returnType)     throws XPathExpressionException;

Parameters item

The starting context (node or node list, for example).

returnType

The desired return type.

returns

The Object that is the result of evaluating the expression and converting the result to re  turnType.

Exceptions XPathExpressionExcep  tion

If the expression cannot be evaluated.

IllegalArgumentException

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants].

NullPointerException

If returnType is null.

Evaluate the compiled XPath expression in the specified context and return the result as the specified type. See Evaluation of XPath Expressions [#XPathExpression-evaluation] for context item evaluation, variable, function and QName resolution and return type conversion. If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants], then an IllegalArgumentException is thrown. If a null value is provided for item, an empty document will be used for the context. If returnType is null, then a NullPointerException is thrown.

Interface XPathFunction XPathFunction provides access to XPath functions. Functions are identified by QName and arity in XPath.

Synopsis implements public XPathFunction { public Object evaluate(java.util.List args)     throws XPathFunctionException;

146

Final 1.0.0

Package javax.xml.xpath

} Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.10 $, $Date: 2004/02/11 20:14:32 $

Since

1.5

Inheritance Path javax.xml.xpath.XPathFunction

Members Method evaluate(List) public Object evaluate(java.util.List args)     throws XPathFunctionException;

Parameters args

The arguments, null is a valid value.

returns

The result of evaluating the XPath function as an Object.

Exceptions XPathFunctionException

If args cannot be evaluated with this XPath function.

Evaluate the function with the specified arguments. To the greatest extent possible, side-effects should be avoided in the definition of extension functions. The implement  ation evaluating an XPath expression is under no obligation to call extension functions in any particular order or any particular number of times.

Interface XPathFunctionResolver XPathFunctionResolver provides access to the set of user defined XPathFunctions. XPath functions are resolved by name and arity. The resolver is not needed for XPath built-in functions and the resolver cannot be used to override those functions. In particular, the resolver is only called for functions in an another namespace (functions with an explicit prefix). This means that you cannot use the XPathFunctionResolver to implement specifications like XML-Signature Syntax and Processing [http://www.w3.org/TR/xmldsig-core/] which extend the function library of XPath 1.0 in the same namespace. This is a consequence of the design of the resolver. If you wish to implement additional built-in functions, you will have to extend the underlying implementation directly.

Synopsis implements public XPathFunctionResolver {

147

Final 1.0.0

Package javax.xml.xpath

public XPathFunction resolveFunction(javax.xml.namespace.QName functionName,                                        int arity); } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.7 $, $Date: 2004/04/01 16:07:17 $

Since

1.5

See Also

XML Path Language (XPath) [http://www.w3.org/TR/xpath#corelib]

Version

1.0,

Core

Function

Library

Inheritance Path javax.xml.xpath.XPathFunctionResolver

Members Method resolveFunction(QName, int) public XPathFunction resolveFunction(javax.xml.namespace.QName functionName,                                        int arity);

Parameters functionName

The function name.

arity

The number of arguments that the returned function must accept.

returns

The function or null if no function named functionName with arity arguments exists.

Exceptions NullPointerException

If functionName or arity is null.

Find a function in the set of available functions. If functionName or arity is null, then a NullPointerException is thrown.

Interface XPathVariableResolver XPathVariableResolver provides access to the set of user defined XPath variables. The XPathVariableResolver and the XPath evaluator must adhere to a contract that cannot be directly enforced by the API. Although variables may be mutable, that is, an application may wish to evaluate the same XPath expression more than once with different variable values, in the course of evaluating any single XPath expression, a variable's value must be immutable.

Synopsis implements public XPathVariableResolver {

148

Final 1.0.0

Package javax.xml.xpath

public Object resolveVariable(javax.xml.namespace.QName variableName); } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.6 $, $Date: 2003/12/08 04:40:47 $

Since

1.5

Inheritance Path javax.xml.xpath.XPathVariableResolver

Members Method resolveVariable(QName) public Object resolveVariable(javax.xml.namespace.QName variableName);

Parameters variableName

The QName118 of the variable name.

returns

The variables value, or null if no variable named variableName exists. The value returned must be of a type appropriate for the underlying object model.

Exceptions NullPointerException

If variableName is null.

Find a variable in the set of available variables. If variableName is null, then a NullPointerException is thrown.

Exception XPathException XPathException represents a generic XPath exception.

Synopsis public XPathException extends Exception { public XPathException(java.lang.String message); public XPathException(java.lang.Throwable cause); public Throwable getCause(); public void printStackTrace(java.io.PrintStream s); public void printStackTrace(); public void printStackTrace(java.io.PrintWriter s);

149

Final 1.0.0

Package javax.xml.xpath

} Author

Norman Walsh [[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.14.12.2 $, $Date: 2004/06/15 00:07:08 $

Since

1.5

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.xpath.XPathException

Members Constructor XPathException(String) public XPathException(java.lang.String message);

Parameters message

The detail message.

Constructs a new XPathException with the specified detail message. The cause is not initialized. If message is null, then a NullPointerException is thrown.

Constructor XPathException(Throwable) public XPathException(java.lang.Throwable cause);

Parameters cause

The cause.

Exceptions NullPointerException

if cause is null.

Constructs a new XPathException with the specified cause. If cause is null, then a NullPointerException is thrown.

150

Final 1.0.0

Package javax.xml.xpath

Exception XPathExpressionException XPathExpressionException represents an error in an XPath expression.

Synopsis public XPathExpressionException extends XPathException { public XPathExpressionException(java.lang.String message); public XPathExpressionException(java.lang.Throwable cause); } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.3.12.1 $, $Date: 2004/06/15 00:05:01 $

Since

1.5

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.xpath.XPathException | javax.xml.xpath.XPathExpressionException

Members Constructor XPathExpressionException(String) public XPathExpressionException(java.lang.String message);

Parameters message

The detail message.

Constructs a new XPathExpressionException with the specified detail message. The cause is not initialized. If message is null, then a NullPointerException is thrown.

151

Final 1.0.0

Package javax.xml.xpath

Constructor XPathExpressionException(Throwable) public XPathExpressionException(java.lang.Throwable cause);

Parameters cause

The cause.

Exceptions NullPointerException

if cause is null.

Constructs a new XPathExpressionException with the specified cause. If cause is null, then a NullPointerException is thrown.

Exception XPathFactoryConfigurationException XPathFactoryConfigurationException represents a configuration error in a XPathFactory131 environment.

Synopsis public XPathFactoryConfigurationException extends XPathException { public XPathFactoryConfigurationException(java.lang.String message); public XPathFactoryConfigurationException(java.lang.Throwable cause); } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.6.12.1 $, $Date: 2004/06/15 00:05:02 $

Since

1.5

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.xpath.XPathException | javax.xml.xpath.XPathFactoryConfigurationException

152

Final 1.0.0

Package javax.xml.xpath

Members Constructor XPathFactoryConfigurationException(String) public XPathFactoryConfigurationException(java.lang.String message);

Parameters message

The detail message.

Constructs a new XPathFactoryConfigurationException with the specified detail message. The cause is not initialized. If message is null, then a NullPointerException is thrown.

Constructor XPathFactoryConfigurationException(Throwable) public XPathFactoryConfigurationException(java.lang.Throwable cause);

Parameters cause

The cause.

Exceptions NullPointerException

if cause is null.

Constructs a new XPathFactoryConfigurationException with the specified cause. If cause is null, then a NullPointerException is thrown.

Exception XPathFunctionException XPathFunctionException represents an error with an XPath function.

Synopsis public XPathFunctionException extends XPathExpressionException { public XPathFunctionException(java.lang.String message); public XPathFunctionException(java.lang.Throwable cause); } Author

Norman Walsh [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.3.12.1 $, $Date: 2004/06/15 00:05:02 $

Since

1.5

153

Final 1.0.0

Package javax.xml.xpath

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.xpath.XPathException | javax.xml.xpath.XPathExpressionException | javax.xml.xpath.XPathFunctionException

Members Constructor XPathFunctionException(String) public XPathFunctionException(java.lang.String message);

Parameters message

The detail message.

Constructs a new XPathFunctionException with the specified detail message. The cause is not initialized. If message is null, then a NullPointerException is thrown.

Constructor XPathFunctionException(Throwable) public XPathFunctionException(java.lang.Throwable cause);

Parameters cause

The cause.

Exceptions NullPointerException

if cause is null.

Constructs a new XPathFunctionException with the specified cause. If cause is null, then a NullPointerException is thrown.

154

Final 1.0.0

Chapter 14. Package 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 con  straining the character data of an XML document. WXS is maintained by the World Wide Web Consortium (W3C) [http://www.w3.org] 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 Inform  ation Standards (OASIS) [http://www.oasis-open.org] and is both an OASIS and an ISO (International Organization for Standardization) [http://www.iso.org] 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 javax.xml.parsers.SAXParser or 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 [#example-1] 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"));

155

Final 1.0.0

Package javax.xml.validation

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 javax.xml.valida  tion.Schema [ Class Schema] with the validation API and associate it with a javax.xml.parsers.DocumentBuilderFactory or a javax.xml.parsers.SAXParserFactory instance by using the javax.xml.parsers.DocumentBuilderFactory#setS  chema(Schema) and 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.

Class Schema Immutable in-memory representation of grammar. This object represents a set of constraints that can be checked/ enforced against an XML document. A javax.xml.validation.Schema [ Class Schema] object is thread safe and applications are encouraged to share it across many parsers in many threads. A javax.xml.validation.Schema [ Class Schema] object is immutable in the sense that it shouldn't change the set of constraints once it is created. In other words, if an application validates the same document twice against the same javax.xml.validation.Schema [ Class Schema], it must always produce the same result. A javax.xml.validation.Schema [ Class Schema] object is usually created from javax.xml.validation.SchemaFactory [ Class SchemaFactory]. Two kinds of validators can be created from a javax.xml.validation.Schema [ Class Schema] object. One is javax.xml.validation.Validator [ Class Validator], which provides highly-level validation operations that cover typical use cases. The other is javax.xml.validation.ValidatorHandler [ Class ValidatorHandler], which works on top of SAX for better modularity. This specification does not refine the java.lang.Object.equals method. In other words, if you parse the same schema twice, you may still get !schemaA.equals(schemaB).

Synopsis public Schema { protected Schema(); public Validator abstract newValidator(); public ValidatorHandler abstract newValidatorHandler();

156

Final 1.0.0

Package javax.xml.validation

} Author

Kohsuke Kawaguchi [mailto:[email protected]]

Version

$Revision: 1.4 $, $Date: 2003/12/06 00:21:36 $

Since

1.5

See Also

XML Schema Part 1: Structures [http://www.w3.org/TR/xmlschema-1/], Extensible Markup Lan  guage (XML) 1.1 [http://www.w3.org/TR/xml11/], Extensible Markup Language (XML) 1.0 (Second Edition) [http://www.w3.org/TR/REC-xml]

Inheritance Path java.lang.Object | javax.xml.validation.Schema

Members Constructor Schema() protected Schema(); Constructor for the derived class. The constructor does nothing.

Method newValidator() public Validator abstract newValidator(); Creates a new javax.xml.validation.Validator [ Class Validator] for this javax.xml.validation.Schema [ Class Schema]. A validator enforces/checks the set of constraints this object represents.

Method newValidatorHandler() public ValidatorHandler abstract newValidatorHandler(); Creates a new javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] for this javax.xml.validation.Schema [ Class Schema].

Class SchemaFactory Factory that creates javax.xml.validation.Schema [ Class Schema] objects. Entry-point to the validation API. javax.xml.validation.SchemaFactory [ Class SchemaFactory] is a schema compiler. It reads external representations of schemas and prepares them for validation. The javax.xml.validation.SchemaFactory [ Class SchemaFactory] class is not thread-safe. In other words, it is the ap  plication's responsibility to ensure that at most one thread is using a javax.xml.validation.SchemaFactory [ Class SchemaFactory] object at any given moment. Implementations are encouraged to mark methods as

157

Final 1.0.0

Package javax.xml.validation

synchronized to protect themselves from broken clients. javax.xml.validation.SchemaFactory [ Class SchemaFactory] is not re-entrant. While one of the newSchema163 methods is being invoked, applications may not attempt to recursively invoke the newSchema163 method, even from the same thread.

Schema Language This spec uses a namespace URI to designate a schema language. The following table shows the values defined by this specification. To be compliant with the spec, the implementation is only required to support W3C XML Schema 1.0. However, if it chooses to support other schema languages listed here, it must conform to the relevant behaviors described in this spec. Schema languages not listed here are expected to introduce their own URIs to represent themselves. The javax.xml.validation.SchemaFactory [ Class SchemaFactory] class is capable of locating other implementations for other schema languages at run-time. Note that because the XML DTD is strongly tied to the parsing process and has a significant effect on the parsing process, it is impossible to define the DTD validation as a process independent from parsing. For this reason, this specification does not define the semantics for the XML DTD. This doesn't prohibit implentors from implementing it in a way they see fit, but users are warned that any DTD validation implemented on this interface necessarily deviate from the XML DTD semantics as defined in the XML 1.0. value

language

j a v a x . x m l . X M L C o n   W3C XML Schema 1.0 stants.W3C_XML_SCHEMA_NS_URI [http://www.w3.org/TR/xmlschema-1] ( " h t   tp://www.w3.org/2001/XMLS  chema") javax.xml.XMLConstants.RE  R E L A X N G LAXNG_NS_URI ("http://re  [http://www.relaxng.org/] laxng.org/ns/struc  ture/1.0")

1 . 0

Synopsis public SchemaFactory { protected SchemaFactory(); static SchemaFactory newInstance(java.lang.String schemaLanguage); public boolean abstract isSchemaLanguageSupported(java.lang.String schemaLanguage); public boolean getFeature(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

158

Final 1.0.0

Package javax.xml.validation

public void setFeature(java.lang.String name,                          boolean value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setProperty(java.lang.String name,                           java.lang.Object object)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public Object getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void abstract setErrorHandler(org.xml.sax.ErrorHandler errorHandler); public ErrorHandler abstract getErrorHandler();

public void abstract setResourceResolver(org.w3c.dom.ls.LSResourceResolver resourceResolver public LSResourceResolver abstract getResourceResolver(); public Schema newSchema(javax.xml.transform.Source schema)     throws org.xml.sax.SAXException; public Schema newSchema(java.io.File schema)     throws org.xml.sax.SAXException; public Schema newSchema(java.net.URL schema)     throws org.xml.sax.SAXException; public Schema abstract newSchema(javax.xml.transform.Source[] schemas)     throws org.xml.sax.SAXException; public Schema abstract newSchema()     throws org.xml.sax.SAXException; } Author

Kohsuke Kawaguchi [mailto:[email protected]]

Version

$Revision: 1.20.10.1.2.2 $, $Date: 2004/06/11 14:59:49 $

Since

1.5

Inheritance Path java.lang.Object | javax.xml.validation.SchemaFactory

Members Constructor SchemaFactory() protected SchemaFactory(); Constructor for derived classes.

159

Final 1.0.0

Package javax.xml.validation

The constructor does nothing. Derived classes must create javax.xml.validation.SchemaFactory [ Class SchemaFactory] objects that have null org.xml.sax.ErrorHandler and null org.w3c.dom.ls.LSResourceResolver.

Method getErrorHandler() public ErrorHandler abstract getErrorHandler(); See Also

javax.xml.validation.SchemaFactory.setErrorHandler [Method setErrorHandler(org.xml.sax.Er  rorHandler)]

Gets the current org.xml.sax.ErrorHandler set to this javax.xml.validation.SchemaFactory [ Class SchemaFactory].

Method getFeature(String) public boolean getFeature(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The feature name, which is a non-null fully-qualified URI.

returns

The current value of the feature (true or false).

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the feature value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.SchemaFactory [ Class SchemaFactory] recognizes the feature name but cannot determine its value at this time.

NullPointerException

if the name parameter is null.

See Also

javax.xml.validation.SchemaFactory.setFeature [Method setFeature(java.lang.String, boolean)]

Look up the value of a feature flag. The feature name is any fully-qualified URI. It is possible for a javax.xml.validation.SchemaFactory [ Class Schema  Factory] to recognize a feature name but temporarily be unable to return its value. Implementors are free (and encouraged) to invent their own features, using names built on their own URIs.

Method getProperty(String) public Object getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The property name, which is a non-null fully-qualified URI.

returns

The current value of the property.

160

Final 1.0.0

Package javax.xml.validation

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the property value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the XMLReader recognizes the property name but cannot determine its value at this time.

NullPointerException

if the name parameter is null.

See Also

javax.xml.validation.SchemaFactory.setProperty java.lang.Object)]

[Method

setProperty(java.lang.String,

Look up the value of a property. The property name is any fully-qualified URI. It is possible for a javax.xml.validation.SchemaFactory [ Class Schem  aFactory] to recognize a property name but temporarily be unable to return its value. javax.xml.validation.SchemaFactory [ Class SchemaFactory]s are not required to recognize any specific property names. Implementors are free (and encouraged) to invent their own properties, using names built on their own URIs.

Method getResourceResolver() public LSResourceResolver abstract getResourceResolver(); See Also

javax.xml.validation.SchemaFactory.setErrorHandler [Method setErrorHandler(org.xml.sax.Er  rorHandler)]

Gets the current org.w3c.dom.ls.LSResourceResolver set to this javax.xml.validation.SchemaFactory [ Class Schema  Factory].

Method isSchemaLanguageSupported(String) public boolean abstract isSchemaLanguageSupported(java.lang.String schemaLanguage);

Parameters schemaLanguage

Specifies the schema language which the returned SchemaFactory157 will understand. schemaLanguage must specify a valid [#schemaLanguage] schema language.

returns

true if SchemaFactory157 supports schemaLanguage, else false.

Exceptions NullPointerException

If schemaLanguage is null.

IllegalArgumentException

If schemaLanguage.length() == 0 or schemaLanguage does not specify a valid [#schemaLanguage] schema language.

Is specified schema supported by this SchemaFactory157?

161

Final 1.0.0

Package javax.xml.validation

Method newInstance(String) static SchemaFactory newInstance(java.lang.String schemaLanguage);

Parameters schemaLanguage

Specifies the schema language which the returned SchemaFactory will understand. See the list of available schema languages [#schemaLanguage] for the possible values.

returns

New instance of a SchemaFactory157

Exceptions IllegalArgumentException

If no implementation of the schema language is available.

NullPointerException

If the

schemLanguage parameter is null. Lookup an implementation of the SchemaFactory157 that supports the specified schema language and return it. To find a SchemaFactory157 object for a given schema language, this method looks the following places in the fol  lowing order where "the class loader" refers to the context class loader: 1.

If the system property "javax.xml.validation.SchemaFactory:schemaLanguage" is present (where schemaLanguage is the parameter to this method), then its value is read as a class name. The method will try to create a new instance of this class by using the class loader, and returns it if it is successfully created.

2.

$java.home/lib/jaxp.properties is read and the value associated with the key being the system property above is looked for. If present, the value is processed just like above.

3.

The class loader is asked for service provider provider-configuration files matching javax.xml.valida  tion.SchemaFactory in the resource directory META-INF/services. See the JAR File Specification for file format and parsing rules. Each potential service provider is required to implement the method:

javax.xml.validation.SchemaFactory.isSchemaLanguageSupported [ Method isSchemaLanguageSupported(java.lang.String)]

The first service provider found in class loader order that supports the specified schema language is returned. 4.

Platform default SchemaFactory157 is located in a implementation specific way. There must be a platform default SchemaFactory157 for W3C XML Schema.

If everything fails, java.lang.IllegalArgumentException will be thrown. Tip for Trouble-shooting: See java.util.Properties.load for exactly how a property file is parsed. In particular, colons ':' need to be escaped in a property file, so make sure schema language URIs are properly escaped in it. For example:

162

Final 1.0.0

Package javax.xml.validation

http\://www.w3.org/2001/XMLSchema=org.acme.foo.XSSchemaFactory

Method newSchema() public Schema abstract newSchema()     throws org.xml.sax.SAXException;

Exceptions UnsupportedOperationEx  ception

If this operation is not supported by the callee.

SAXException

If this operation is supported but failed for some reason.

Creates a special javax.xml.validation.Schema [ Class Schema] object. The exact semantics of the returned javax.xml.validation.Schema [ Class Schema] object depends on the schema language that this javax.xml.validation.SchemaFactory [ Class SchemaFactory] is created for. Also, implementations are allowed to use implementation-specific property/feature to alter the semantics of this method.

W3C XML Schema 1.0 For XML Schema, this method creates a javax.xml.validation.Schema [ Class Schema] object that performs validation by using location hints specified in documents. The returned javax.xml.validation.Schema [ Class Schema] object assumes that if documents refer to the same URL in the schema location hints, they will always resolve to the same schema document. This asusmption allows imple  mentations to reuse parsed results of schema documents so that multiple validations against the same schema will run faster. Note that the use of schema location hints introduces a vulnerability to denial-of-service attacks. RELAX NG RELAX NG does not support this operation.

Method newSchema(File) public Schema newSchema(java.io.File schema)     throws org.xml.sax.SAXException;

Parameters schema

File that represents a schema.

returns

New Schema156 from parsing schema.

Exceptions SAXException

If a SAX error occurs during parsing.

163

Final 1.0.0

Package javax.xml.validation

NullPointerException

if

schema is null. Parses the specified File as a schema and returns it as a Schema156. This is a convenience method for javax.xml.validation.SchemaFactory.newSchema [ Method newSchema(javax.xml.trans  form.Source)].

Method newSchema(Source) public Schema newSchema(javax.xml.transform.Source schema)     throws org.xml.sax.SAXException;

Parameters schema

Source that represents a schema.

returns

New Schema156 from parsing schema.

Exceptions SAXException

If a SAX error occurs during parsing.

NullPointerException

if

schema is null. Parses the specified source as a schema and returns it as a schema. This is a convenience method for javax.xml.validation.SchemaFactory.newSchema [ Method newSchema(javax.xml.trans  form.Source[])].

Method newSchema(Source[]) public Schema abstract newSchema(javax.xml.transform.Source[] schemas)     throws org.xml.sax.SAXException;

Parameters schemas

inputs to be parsed. javax.xml.validation.SchemaFactory [ Class SchemaFactory] is required to re  cognize javax.xml.transform.sax.SAXSource, javax.xml.transform.stream.StreamSource, and javax.xml.transform.dom.DOMSource.

returns

Always return a non-null valid javax.xml.validation.Schema [ Class Schema] object. Note that when an error has been reported, there is no guarantee that the returned javax.xml.validation.Schema [ Class Schema] object is meaningful.

164

Final 1.0.0

Package javax.xml.validation

Exceptions SAXException

If an error is found during processing the specified inputs. When an org.xml.sax.Er  rorHandler is set, errors are reported to there first. See javax.xml.validation.SchemaFact  ory.setErrorHandler [ Method setErrorHandler(org.xml.sax.ErrorHandler)].

NullPointerException

If the schemas parameter itself is null or any item in the array is null.

IllegalArgumentException

If any item in the array is not recognized by this method.

UnsupportedOperationEx  ception

If the schema language doesn't support this operation.

Parses the specified source(s) as a schema and returns it as a schema. The callee will read all the javax.xml.transform.Sources and combine them into a single schema. The exact semantics of the combination depends on the schema language that this javax.xml.validation.SchemaFactory [ Class SchemaFactory] object is created for. When an org.xml.sax.ErrorHandler is set, the callee will report all the errors found in sources to the handler. If the handler throws an exception, it will abort the schema compilation and the same exception will be thrown from this method. Also, after an error is reported to a handler, the callee is allowed to abort the further processing by throwing it. If an error handler is not set, the callee will throw the first error it finds in the sources.

W3C XML Schema 1.0 The resulting schema contains components from the specified sources. The same result would be achieved if all these sources were imported, using appropriate values for schemaLocation and namespace, into a single schema document with a different targetNamespace and no components of its own, if the import elements were given in the same order as the sources. Section 4.2.3 of the XML Schema recommendation describes the options processors have in this regard. While a processor should be consistent in its treatment of JAXP schema sources and XML Schema imports, the behaviour between JAXP-compliant parsers may vary; in particular, parsers may choose to ignore all but the first for a given namespace, regardless of information provided in schemaLocation. If the parsed set of schemas includes error(s) as specified in the section 5.1 of the XML Schema spec, then the error must be reported to the org.xml.sax.ErrorHandler. RELAX NG For RELAX NG, this method must throw java.lang.UnsupportedOperationException if

schemas.length!=1 .

Method newSchema(URL) public Schema newSchema(java.net.URL schema)     throws org.xml.sax.SAXException;

Parameters schema

URL that represents a schema.

165

Final 1.0.0

Package javax.xml.validation

returns

New Schema156 from parsing schema.

Exceptions SAXException

If a SAX error occurs during parsing.

NullPointerException

if

schema is null. Parses the specified URL as a schema and returns it as a Schema156. This is a convenience method for javax.xml.validation.SchemaFactory.newSchema [ Method newSchema(javax.xml.trans  form.Source)].

Method setErrorHandler(ErrorHandler) public void abstract setErrorHandler(org.xml.sax.ErrorHandler errorHandler);

Parameters errorHandler

A new error handler to be set. This parameter can be null.

Sets the org.xml.sax.ErrorHandler to receive errors encountered during the newSchema163 method invocation. Error handler can be used to customize the error handling process during schema parsing. When an org.xml.sax.Er  rorHandler is set, errors found during the parsing of schemas will be first sent to the org.xml.sax.ErrorHandler. The error handler can abort the parsing of a schema immediately by throwing org.xml.sax.SAXException from the handler. Or for example it can print an error to the screen and try to continue the processing by returning normally from the org.xml.sax.ErrorHandler If any java.lang.Throwable (or instances of its derived classes) is thrown from an org.xml.sax.ErrorHandler, the caller of the newSchema163 method will be thrown the same java.lang.Throwable object. javax.xml.validation.SchemaFactory [ Class SchemaFactory] is not allowed to throw org.xml.sax.SAXException without first reporting it to org.xml.sax.ErrorHandler. Applications can call this method even during a javax.xml.validation.Schema [ Class Schema] is being parsed. When the org.xml.sax.ErrorHandler is null, the implementation will behave as if the following org.xml.sax.ErrorHandler is set:

class DraconianErrorHandler implements org.xml.sax.ErrorHandler { public void fatalError( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { throw e; }

166

Final 1.0.0

Package javax.xml.validation

public void error( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { throw e; } public void warning( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { // noop } }

When a new javax.xml.validation.SchemaFactory [ Class SchemaFactory] object is created, initially this field is set to null. This field will NOT be inherited to javax.xml.validation.Schema [ Class Schema]s, javax.xml.validation.Val  idator [ Class Validator]s, or javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]s that are created from this javax.xml.validation.SchemaFactory [ Class SchemaFactory].

Method setFeature(String, boolean) public void setFeature(java.lang.String name,                          boolean value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The feature name, which is a non-null fully-qualified URI.

value

The requested value of the feature (true or false).

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the feature value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.SchemaFactory [ Class SchemaFactory] recognizes the feature name but cannot set the requested value.

NullPointerException

if the name parameter is null.

See Also

javax.xml.validation.SchemaFactory.getFeature [Method getFeature(java.lang.String)]

Set the value of a feature flag. Feature can be used to control the way a javax.xml.validation.SchemaFactory [ Class SchemaFactory] parses schemas, although javax.xml.validation.SchemaFactory [ Class SchemaFactory]s are not required to recognize any specific feature names. The feature name is any fully-qualified URI. It is possible for a javax.xml.validation.SchemaFactory [ Class Schema  Factory] to expose a feature value but to be unable to change the current value. All implementations are required to support the javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING feature. When the feature is:

167

Final 1.0.0

Package javax.xml.validation



true: the implementation will limit XML processing to conform to implementation limits. Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources. If XML processing is limited for security reasons, it will be reported via a call to the registered org.xml.sax.ErrorHandler.fatalError. See javax.xml.validation.SchemaFactory.setErrorHandler [ Method setErrorHandler(org.xml.sax.ErrorHandler)].



false: the implementation will processing XML according to the XML specifications without regard to possible implementation limits.

Method setProperty(String, Object) public void setProperty(java.lang.String name,                           java.lang.Object object)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The property name, which is a non-null fully-qualified URI.

object

The requested value for the property.

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the property value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.SchemaFactory [ Class SchemaFactory] recognizes the property name but cannot set the requested value.

NullPointerException

if the name parameter is null.

Set the value of a property. The property name is any fully-qualified URI. It is possible for a javax.xml.validation.SchemaFactory [ Class Schem  aFactory] to recognize a property name but to be unable to change the current value. javax.xml.validation.SchemaFactory [ Class SchemaFactory]s are not required to recognize setting any specific property names.

Method setResourceResolver(LSResourceResolver)

public void abstract setResourceResolver(org.w3c.dom.ls.LSResourceResolver resourceResolver

Parameters resourceResolver

A new resource resolver to be set. This parameter can be null.

Sets the org.w3c.dom.ls.LSResourceResolver to customize resource resolution when parsing schemas. javax.xml.validation.SchemaFactory [ Class SchemaFactory] uses a org.w3c.dom.ls.LSResourceResolver when it needs to locate external resources while parsing schemas, although exactly what constitutes "locating external resources" is up to each schema language. For example, for W3C XML Schema, this includes files



168

Final 1.0.0

Package javax.xml.validation

d or

ed, and DTD referenced from schema files, etc. Applications can call this method even during a javax.xml.validation.Schema [ Class Schema] is being parsed. When the org.w3c.dom.ls.LSResourceResolver is null, the implementation will behave as if the following org.w3c.dom.ls.LSResourceResolver is set:

class DumbDOMResourceResolver implements org.w3c.dom.ls.LSResourceResolver { public org.w3c.dom.ls.LSInput resolveResource( String publicId, String systemId, String baseURI) { return null; // always return null } }

If a org.w3c.dom.ls.LSResourceResolver throws a java.lang.RuntimeException (or instances of its derived classes), then the javax.xml.validation.SchemaFactory [ Class SchemaFactory] will abort the parsing and the caller of the newSchema163 method will receive the same java.lang.RuntimeException. When a new javax.xml.validation.Schem  aFactory [ Class SchemaFactory] object is created, initially this field is set to null. This field will NOT be inherited to javax.xml.validation.Schema [ Class Schema]s, javax.xml.validation.Validator [ Class Validator]s, or javax.xml.valid  ation.ValidatorHandler [ Class ValidatorHandler]s that are created from this javax.xml.validation.SchemaFactory [ Class SchemaFactory].

Class TypeInfoProvider This class provides access to the type information determined by javax.xml.validation.ValidatorHandler [ Class Valid  atorHandler]. Some schema languages, such as W3C XML Schema, encourages a validator to report the "type" it assigns to each attribute/element. Those applications who wish to access this type information can invoke methods defined on this "interface" to access such type information. Implementation of this "interface" can be obtained through the javax.xml.validation.ValidatorHandler.getTypeInfoPro  vider [ Method getTypeInfoProvider()] method.

Synopsis public TypeInfoProvider { protected TypeInfoProvider(); public TypeInfo abstract getElementTypeInfo(); public TypeInfo abstract getAttributeTypeInfo(int index);

169

Final 1.0.0

Package javax.xml.validation

public boolean abstract isIdAttribute(int index); public boolean abstract isSpecified(int index); } Author

Kohsuke Kawaguchi [mailto:[email protected]]

Version

$Revision: 1.11 $, $Date: 2004/02/06 01:16:10 $

Since

1.5

See Also

org.w3c.dom.TypeInfo

Inheritance Path java.lang.Object | javax.xml.validation.TypeInfoProvider

Members Constructor TypeInfoProvider() protected TypeInfoProvider(); Constructor for the derived class. The constructor does nothing.

Method getAttributeTypeInfo(int) public TypeInfo abstract getAttributeTypeInfo(int index);

Parameters index

The index of the attribute. The same index for the org.xml.sax.Attributes object passed to the

startElement callback. returns

An immutable org.w3c.dom.TypeInfo object that represents the type of the specified attribute. Note that the caller can keep references to the obtained org.w3c.dom.TypeInfo longer than the callback scope. Otherwise, this method returns null if the validator is unable to determine the type.

Exceptions IndexOutOfBoundsExcep  tion

If the index is invalid.

IllegalStateException

If this method is called from other org.xml.sax.ContentHandler methods.

Returns the immutable org.w3c.dom.TypeInfo object for the specified attribute of the current element.

170

Final 1.0.0

Package javax.xml.validation

The method may only be called by the startElement event of the org.xml.sax.ContentHandler that the application sets to the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler].

Method getElementTypeInfo() public TypeInfo abstract getElementTypeInfo();

Exceptions IllegalStateException

If this method is called from other org.xml.sax.ContentHandler methods.

Returns the immutable org.w3c.dom.TypeInfo object for the current element. The method may only be called by the startElement event of the org.xml.sax.ContentHandler that the application sets to the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler].

Method isIdAttribute(int) public boolean abstract isIdAttribute(int index);

Parameters index

The index of the attribute. The same index for the org.xml.sax.Attributes object passed to the

startElement callback. returns

true if the type of the specified attribute is ID.

Exceptions IndexOutOfBoundsExcep  tion

If the index is invalid.

IllegalStateException

If this method is called from other org.xml.sax.ContentHandler methods.

Returns

true if the specified attribute is determined to be ID. Exacly how an attribute is "determined to be ID" is up to the schema language. In case of W3C XML Schema, this means that the actual type of the attribute is the built-in ID type or its derived type. A javax.xml.parsers.DocumentBuilder uses this information to properly implement org.w3c.dom.Attr.isId. The method may only be called by the startElement event of the org.xml.sax.ContentHandler that the application sets to the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler].

171

Final 1.0.0

Package javax.xml.validation

Method isSpecified(int) public boolean abstract isSpecified(int index);

Parameters index

The index of the attribute. The same index for the org.xml.sax.Attributes object passed to the

startElement callback. returns true if the attribute was present before the validator processes input.

false if the attribute was added by the validator.

Exceptions IndexOutOfBoundsExcep  tion

If the index is invalid.

IllegalStateException

If this method is called from other org.xml.sax.ContentHandler methods.

Returns

false if the attribute was added by the validator. This method provides information necessary for a javax.xml.parsers.DocumentBuilder to determine what the DOM tree should return from the org.w3c.dom.Attr.getSpecified method. The method may only be called by the startElement event of the org.xml.sax.ContentHandler that the application sets to the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]. A general guideline for validators is to return true if the attribute was originally present in the pipeline, and false if it was added by the validator.

Class Validator A processor that checks an XML document against javax.xml.validation.Schema [ Class Schema]. A validator is a thread-unsafe and non-reentrant object. In other words, it is the application's responsibility to make sure that one javax.xml.validation.Validator [ Class Validator] object is not used from more than one thread at any given time, and while the

172

Final 1.0.0

Package javax.xml.validation

validate method is invoked, applications may not recursively call the

validate method. Note that while the javax.xml.validation.Validator.validate [ Method validate(javax.xml.transform.Source)] and javax.xml.validation.Validator.validate [ Method validate(javax.xml.transform.Source, javax.xml.transform.Result)] methods take a javax.xml.transform.Source instance, the Source instance must be a SAXSource101 or DOMSource95.

Synopsis public Validator { protected Validator(); public void abstract reset(); public void validate(javax.xml.transform.Source source)     throws org.xml.sax.SAXException, java.io.IOException; public void abstract validate(javax.xml.transform.Source source,                                 javax.xml.transform.Result result)     throws org.xml.sax.SAXException, java.io.IOException; public void abstract setErrorHandler(org.xml.sax.ErrorHandler errorHandler); public ErrorHandler abstract getErrorHandler();

public void abstract setResourceResolver(org.w3c.dom.ls.LSResourceResolver resourceResolver public LSResourceResolver abstract getResourceResolver(); public boolean getFeature(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setFeature(java.lang.String name,                          boolean value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setProperty(java.lang.String name,                           java.lang.Object object)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public Object getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; } Author

Kohsuke Kawaguchi [mailto:[email protected]]

Version

$Revision: 1.18.14.1.2.4 $, $Date: 2004/07/13 22:27:52 $

173

Final 1.0.0

Package javax.xml.validation

Since

1.5

Inheritance Path java.lang.Object | javax.xml.validation.Validator

Members Constructor Validator() protected Validator(); Constructor for derived classes. The constructor does nothing. Derived classes must create javax.xml.validation.Validator [ Class Validator] objects that have

null org.xml.sax.ErrorHandler and

null org.w3c.dom.ls.LSResourceResolver.

Method getErrorHandler() public ErrorHandler abstract getErrorHandler(); See Also

javax.xml.validation.Validator.setErrorHandler [Method setErrorHandler(org.xml.sax.ErrorHandler)]

Gets the current org.xml.sax.ErrorHandler set to this javax.xml.validation.Validator [ Class Validator].

Method getFeature(String) public boolean getFeature(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The feature name, which is a non-null fully-qualified URI.

returns

The current value of the feature (true or false).

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the feature value can't be assigned or retrieved.

174

Final 1.0.0

Package javax.xml.validation

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.Validator [ Class Validator] recognizes the feature name but cannot determine its value at this time.

NullPointerException

When the name parameter is null.

See Also

javax.xml.validation.Validator.setFeature [Method setFeature(java.lang.String, boolean)]

Look up the value of a feature flag. The feature name is any fully-qualified URI. It is possible for a javax.xml.validation.Validator [ Class Validator] to recognize a feature name but temporarily be unable to return its value. Some feature values may be available only in specific contexts, such as before, during, or after a validation. Implementors are free (and encouraged) to invent their own features, using names built on their own URIs.

Method getProperty(String) public Object getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The property name, which is a non-null fully-qualified URI.

returns

The current value of the property.

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the property value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the XMLReader recognizes the property name but cannot determine its value at this time.

NullPointerException

When the name parameter is null.

See Also

javax.xml.validation.Validator.setProperty [Method setProperty(java.lang.String, java.lang.Object)]

Look up the value of a property. The property name is any fully-qualified URI. It is possible for a javax.xml.validation.Validator [ Class Validator] to recognize a property name but temporarily be unable to return its value. Some property values may be available only in specific contexts, such as before, during, or after a validation. javax.xml.validation.Validator [ Class Validator]s are not required to recognize any specific property names. Implementors are free (and encouraged) to invent their own properties, using names built on their own URIs.

Method getResourceResolver() public LSResourceResolver abstract getResourceResolver(); See Also

javax.xml.validation.Validator.setErrorHandler [Method setErrorHandler(org.xml.sax.ErrorHandler)]

Gets the current org.w3c.dom.ls.LSResourceResolver set to this javax.xml.validation.Validator [ Class Validator].

175

Final 1.0.0

Package javax.xml.validation

Method reset() public void abstract reset(); Reset this Validator172 to its original configuration. Validator172 is reset to the same state as when it was created with javax.xml.validation.Schema.newValidator [ Method newValidator()]. reset() is designed to allow the reuse of existing Validator172s thus saving resources associated with the creation of new Validator172s. The reset Validator172 is not guaranteed to have the same org.w3c.dom.ls.LSResourceResolver or org.xml.sax.Er  rorHandler Objects, e.g. java.lang.Object.equals. It is guaranteed to have a functionally equal LSResourceResolv  er and ErrorHandler.

Method setErrorHandler(ErrorHandler) public void abstract setErrorHandler(org.xml.sax.ErrorHandler errorHandler);

Parameters errorHandler

A new error handler to be set. This parameter can be null.

Sets the org.xml.sax.ErrorHandler to receive errors encountered during the validate method invocation. Error handler can be used to customize the error handling process during a validation. When an org.xml.sax.ErrorHandler is set, errors found during the validation will be first sent to the org.xml.sax.ErrorHandler. The error handler can abort further validation immediately by throwing org.xml.sax.SAXException from the handler. Or for example it can print an error to the screen and try to continue the validation by returning normally from the org.xml.sax.ErrorHandler If any java.lang.Throwable is thrown from an org.xml.sax.ErrorHandler, the caller of the validate method will be thrown the same java.lang.Throwable object. javax.xml.validation.Validator [ Class Validator] is not allowed to throw org.xml.sax.SAXException without first re  porting it to org.xml.sax.ErrorHandler. When the org.xml.sax.ErrorHandler is null, the implementation will behave as if the following org.xml.sax.ErrorHandler is set:

class DraconianErrorHandler implements org.xml.sax.ErrorHandler { public void fatalError( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { throw e; } public void error( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { throw e; }

176

Final 1.0.0

Package javax.xml.validation

public void warning( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { // noop } }

When a new javax.xml.validation.Validator [ Class Validator] object is created, initially this field is set to null.

Method setFeature(String, boolean) public void setFeature(java.lang.String name,                          boolean value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The feature name, which is a non-null fully-qualified URI.

value

The requested value of the feature (true or false).

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the feature value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.Validator [ Class Validator] recognizes the feature name but cannot set the requested value.

NullPointerException

When the name parameter is null.

See Also

javax.xml.validation.Validator.getFeature [Method getFeature(java.lang.String)]

Set the value of a feature flag. Feature can be used to control the way a javax.xml.validation.Validator [ Class Validator] parses schemas, although javax.xml.validation.Validator [ Class Validator]s are not required to recognize any specific property names. The feature name is any fully-qualified URI. It is possible for a javax.xml.validation.Validator [ Class Validator] to expose a feature value but to be unable to change the current value. Some feature values may be immutable or mutable only in specific contexts, such as before, during, or after a validation.

Method setProperty(String, Object) public void setProperty(java.lang.String name,                           java.lang.Object object)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The property name, which is a non-null fully-qualified URI.

object

The requested value for the property.

177

Final 1.0.0

Package javax.xml.validation

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the property value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.Validator [ Class Validator] recognizes the property name but cannot set the requested value.

NullPointerException

When the name parameter is null.

Set the value of a property. The property name is any fully-qualified URI. It is possible for a javax.xml.validation.Validator [ Class Validator] to recognize a property name but to be unable to change the current value. Some property values may be immutable or mutable only in specific contexts, such as before, during, or after a validation. javax.xml.validation.Validator [ Class Validator]s are not required to recognize setting any specific property names.

Method setResourceResolver(LSResourceResolver)

public void abstract setResourceResolver(org.w3c.dom.ls.LSResourceResolver resourceResolver

Parameters resourceResolver

A new resource resolver to be set. This parameter can be null.

Sets the org.w3c.dom.ls.LSResourceResolver to customize resource resolution while in a validation episode. javax.xml.validation.Validator [ Class Validator] uses a org.w3c.dom.ls.LSResourceResolver when it needs to locate external resources while a validation, although exactly what constitutes "locating external resources" is up to each schema language. When the org.w3c.dom.ls.LSResourceResolver is null, the implementation will behave as if the following org.w3c.dom.ls.LSResourceResolver is set:

class DumbLSResourceResolver implements org.w3c.dom.ls.LSResourceResolver { public org.w3c.dom.ls.LSInput resolveResource( String publicId, String systemId, String baseURI) { return null; // always return null } }

If a org.w3c.dom.ls.LSResourceResolver throws a java.lang.RuntimeException (or instances of its derived classes), then the javax.xml.validation.Validator [ Class Validator] will abort the parsing and the caller of the validate method will receive the same java.lang.RuntimeException. When a new javax.xml.validation.Validator [ Class Valid  ator] object is created, initially this field is set to null.

178

Final 1.0.0

Package javax.xml.validation

Method validate(Source) public void validate(javax.xml.transform.Source source)     throws org.xml.sax.SAXException, java.io.IOException; See Also

javax.xml.validation.Validator.setErrorHandler [Method setErrorHandler(org.xml.sax.ErrorHandler)]

Validates the specified input. This is just a convenience method of:

validate(source,null);

Method validate(Source, Result) public void abstract validate(javax.xml.transform.Source source,                                 javax.xml.transform.Result result)     throws org.xml.sax.SAXException, java.io.IOException;

Parameters source

XML to be validated. Must not be null.

result

The javax.xml.transform.Result object that receives (possibly augmented) XML. This parameter can be null if the caller is not interested in it. Note that when a javax.xml.transform.dom.DOMResult is used, a validator might just pass the same DOM node from javax.xml.transform.dom.DOMSource to javax.xml.transform.dom.DOMResult (in which case

source.getNode()==result.getNode() ), it might copy the entire DOM tree, or it might alter the node given by the source.

Exceptions IllegalArgumentException

If the javax.xml.transform.Result type doesn't match the javax.xml.transform.Source type, or if the specified source is neither javax.xml.transform.sax.SAXSource nor javax.xml.transform.dom.DOMSource.

SAXException

If the org.xml.sax.ErrorHandler throws a org.xml.sax.SAXException or if a fatal error is found and the org.xml.sax.ErrorHandler returns normally.

IOException

If the validator is processing a javax.xml.transform.sax.SAXSource and the underlying org.xml.sax.XMLReader throws an java.io.IOException.

NullPointerException

If the

source parameter is null.

179

Final 1.0.0

Package javax.xml.validation

See Also

javax.xml.validation.Validator.validate [Method validate(javax.xml.transform.Source)]

Validates the specified input and send the augmented validation result to the specified output. This method places the following restrictions on the types of the javax.xml.transform.Source/ javax.xml.transform.Result accepted.

javax.xml.transform.Source/javax.xml.transform.Result accepted: javax.xml.transform.sax.SAXSource javax.xml.transform.dom.DOMSource OK

OK

OK

Err

javax.xml.transform.dom.DOMResult Err

OK

null javax.xml.transform.sax.SAXResult

Note that javax.xml.transform.stream.StreamSource instances are not allowed. To process a StreamSource113, or to validate one javax.xml.transform.Source into another kind of javax.xml.transform.Result, use the identity transformer (see javax.xml.transform.TransformerFactory.newTransformer). Errors found during the validation is sent to the specified org.xml.sax.ErrorHandler. If a document is valid, or if a document contains some errors but none of them were fatal and the org.xml.sax.ErrorHand  ler didn't throw any exception, then the method returns normally.

Class ValidatorHandler Streaming validator that works on SAX stream. A javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] object is a thread-unsafe, non-reentrant object. In other words, it is the application's responsibility to make sure that one javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] object is not used from more than one thread at any given time. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] checks if the SAX events follow the set of constraints described in the associated javax.xml.validation.Schema [ Class Schema], and additionally it may modify the SAX events (for example by adding default values, etc.) javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] extends from org.xml.sax.ContentHandler, but it refines the underlying org.xml.sax.ContentHandler in the following way: 1.

startElement/endElement events must receive non-null String for uri, localName, and qname, even though SAX allows some of them to be null. Similarly, the user-specified org.xml.sax.ContentHandler will receive nonnull Strings for all three parameters.

2.

Applications must ensure that javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]'s org.xml.sax.ContentHandler.startPrefixMapping and org.xml.sax.ContentHandler.endPrefixMapping are invoked properly. Similarly, the user-specified org.xml.sax.ContentHandler will receive startPrefixMapping/endPrefixMap  ping events. If the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] introduces additional namespace bindings, the user-specified org.xml.sax.ContentHandler will receive additional startPrefixMapping/endPrefixMap  ping events.

3.

org.xml.sax.Attributes for the org.xml.sax.ContentHandler.startElement method may or may not include xmlns* attributes.

180

Final 1.0.0

Package javax.xml.validation

A javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] is automatically reset every time the startDocument method is invoked.

Recognized Properties and Features This spec defines the following feature that must be recognized by all javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] implementations.

http://xml.org/sax/features/namespace-prefixes This feature controls how a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] introduces namespace bindings that were not present in the original SAX event stream. When this feature is set to true, it must make sure that the user's org.xml.sax.ContentHandler will see the corresponding xmlns* attribute in the org.xml.sax.Attributes object of the org.xml.sax.ContentHandler.startElement callback. Otherwise, xmlns* attributes must not be added to org.xml.sax.Attributes that's passed to the user-specified org.xml.sax.ContentHandler. (Note that regardless of this switch, namespace bindings are always notified to applications through org.xml.sax.Con  tentHandler.startPrefixMapping and org.xml.sax.ContentHandler.endPrefixMapping methods of the org.xml.sax.ContentHandler specified by the user.) Note that this feature does NOT affect the way a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] receives SAX events. It merely changes the way it augments SAX events. This feature is set to false by default.

Synopsis public ValidatorHandlerimplements ContentHandler { protected ValidatorHandler(); public void abstract setContentHandler(org.xml.sax.ContentHandler receiver); public ContentHandler abstract getContentHandler(); public void abstract setErrorHandler(org.xml.sax.ErrorHandler errorHandler); public ErrorHandler abstract getErrorHandler();

public void abstract setResourceResolver(org.w3c.dom.ls.LSResourceResolver resourceResolver public LSResourceResolver abstract getResourceResolver(); public TypeInfoProvider abstract getTypeInfoProvider(); public boolean getFeature(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setFeature(java.lang.String name,                          boolean value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; public void setProperty(java.lang.String name,                           java.lang.Object object)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

181

Final 1.0.0

Package javax.xml.validation

public Object getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException; } Author

Kohsuke Kawaguchi [mailto:[email protected]]

Version

$Revision: 1.23.16.1 $, $Date: 2004/06/28 18:26:43 $

Since

1.5

Inheritance Path java.lang.Object | javax.xml.validation.ValidatorHandler

Members Constructor ValidatorHandler() protected ValidatorHandler(); Constructor for derived classes. The constructor does nothing. Derived classes must create javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] objects that have

null org.xml.sax.ErrorHandler and

null org.w3c.dom.ls.LSResourceResolver.

Method getContentHandler() public ContentHandler abstract getContentHandler(); See Also

javax.xml.validation.ValidatorHandler.setContentHandler ler(org.xml.sax.ContentHandler)]

[Method

setContentHand 

Gets the org.xml.sax.ContentHandler which receives the augmented validation result.

Method getErrorHandler() public ErrorHandler abstract getErrorHandler(); See Also

javax.xml.validation.ValidatorHandler.setErrorHandler [Method setErrorHandler(org.xml.sax.Er  rorHandler)]

182

Final 1.0.0

Package javax.xml.validation

Gets the current org.xml.sax.ErrorHandler set to this javax.xml.validation.ValidatorHandler [ Class ValidatorHandler].

Method getFeature(String) public boolean getFeature(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The feature name, which is a non-null fully-qualified URI.

returns

The current value of the feature (true or false).

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the feature value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] recognizes the feature name but cannot determine its value at this time.

NullPointerException

When the name parameter is null.

See Also

javax.xml.validation.ValidatorHandler.setFeature [Method setFeature(java.lang.String, boolean)]

Look up the value of a feature flag. The feature name is any fully-qualified URI. It is possible for a javax.xml.validation.ValidatorHandler [ Class Valid  atorHandler] to recognize a feature name but temporarily be unable to return its value. Some feature values may be available only in specific contexts, such as before, during, or after a validation. Implementors are free (and encouraged) to invent their own features, using names built on their own URIs.

Method getProperty(String) public Object getProperty(java.lang.String name)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The property name, which is a non-null fully-qualified URI.

returns

The current value of the property.

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the property value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the XMLReader recognizes the property name but cannot determine its value at this time.

NullPointerException

When the name parameter is null.

183

Final 1.0.0

Package javax.xml.validation

See Also

javax.xml.validation.ValidatorHandler.setProperty java.lang.Object)]

[Method

setProperty(java.lang.String,

Look up the value of a property. The property name is any fully-qualified URI. It is possible for a javax.xml.validation.ValidatorHandler [ Class Valid  atorHandler] to recognize a property name but temporarily be unable to return its value. Some property values may be available only in specific contexts, such as before, during, or after a validation. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]s are not required to recognize any specific property names. Implementors are free (and encouraged) to invent their own properties, using names built on their own URIs.

Method getResourceResolver() public LSResourceResolver abstract getResourceResolver(); See Also

javax.xml.validation.ValidatorHandler.setErrorHandler [Method setErrorHandler(org.xml.sax.Er  rorHandler)]

Gets the current org.w3c.dom.ls.LSResourceResolver set to this javax.xml.validation.ValidatorHandler [ Class Valid  atorHandler].

Method getTypeInfoProvider() public TypeInfoProvider abstract getTypeInfoProvider(); Obtains the javax.xml.validation.TypeInfoProvider [ Class TypeInfoProvider] implementation of this javax.xml.valid  ation.ValidatorHandler [ Class ValidatorHandler]. The obtained javax.xml.validation.TypeInfoProvider [ Class TypeInfoProvider] can be queried during a parse to access the type information determined by the validator. Some schema languages do not define the notion of type, for those languages, this method may not be supported. However, to be compliant with this specification, implementations for W3C XML Schema 1.0 must support this oper  ation.

Method setContentHandler(ContentHandler) public void abstract setContentHandler(org.xml.sax.ContentHandler receiver);

Parameters receiver

A org.xml.sax.ContentHandler or a null value.

Sets the org.xml.sax.ContentHandler which receives the augmented validation result. When a org.xml.sax.ContentHandler is specified, a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] will work as a filter and basically copy the incoming events to the specified org.xml.sax.ContentHandler. In doing so, a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may modify the events, for example by adding defaulted attributes.

184

Final 1.0.0

Package javax.xml.validation

A javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may buffer events to certain extent, but to allow javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] to be used by a parser, the following requirement has to be met. 1.

When org.xml.sax.ContentHandler.startElement, org.xml.sax.ContentHandler.endElement, org.xml.sax.Con  tentHandler.startDocument, or org.xml.sax.ContentHandler.endDocument are invoked on a javax.xml.valida  tion.ValidatorHandler [ Class ValidatorHandler], the same method on the user-specified org.xml.sax.ContentHandler must be invoked for the same event before the callback returns.

2.

javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may not introduce new elements that were not present in the input.

3.

javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may not remove attributes that were present in the input.

When a callback method on the specified org.xml.sax.ContentHandler throws an exception, the same exception object must be thrown from the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]. The org.xml.sax.ErrorHandler should not be notified of such an exception. This method can be called even during a middle of a validation.

Method setErrorHandler(ErrorHandler) public void abstract setErrorHandler(org.xml.sax.ErrorHandler errorHandler);

Parameters errorHandler

A new error handler to be set. This parameter can be null.

Sets the org.xml.sax.ErrorHandler to receive errors encountered during the validation. Error handler can be used to customize the error handling process during a validation. When an org.xml.sax.ErrorHandler is set, errors found during the validation will be first sent to the org.xml.sax.ErrorHandler. The error handler can abort further validation immediately by throwing org.xml.sax.SAXException from the handler. Or for example it can print an error to the screen and try to continue the validation by returning normally from the org.xml.sax.ErrorHandler If any java.lang.Throwable is thrown from an org.xml.sax.ErrorHandler, the same java.lang.Throwable object will be thrown toward the root of the call stack. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] is not allowed to throw org.xml.sax.SAXException without first reporting it to org.xml.sax.ErrorHandler. When the org.xml.sax.ErrorHandler is null, the implementation will behave as if the following org.xml.sax.ErrorHandler is set:

class DraconianErrorHandler implements org.xml.sax.ErrorHandler { public void fatalError( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { throw e;

185

Final 1.0.0

Package javax.xml.validation

} public void error( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { throw e; } public void warning( org.xml.sax.SAXParseException e ) throws org.xml.sax.SAXException { // noop } }

When a new javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] object is created, initially this field is set to null.

Method setFeature(String, boolean) public void setFeature(java.lang.String name,                          boolean value)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The feature name, which is a non-null fully-qualified URI.

value

The requested value of the feature (true or false).

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the feature value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] recognizes the feature name but cannot set the requested value.

NullPointerException

When the name parameter is null.

See Also

javax.xml.validation.ValidatorHandler.getFeature [Method getFeature(java.lang.String)]

Set the value of a feature flag. Feature can be used to control the way a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] parses schemas, although javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]s are not required to recognize any specific property names. The feature name is any fully-qualified URI. It is possible for a javax.xml.validation.ValidatorHandler [ Class Valid  atorHandler] to expose a feature value but to be unable to change the current value. Some feature values may be im  mutable or mutable only in specific contexts, such as before, during, or after a validation.

186

Final 1.0.0

Package javax.xml.validation

Method setProperty(String, Object) public void setProperty(java.lang.String name,                           java.lang.Object object)     throws org.xml.sax.SAXNotRecognizedException, org.xml.sax.SAXNotSupportedException;

Parameters name

The property name, which is a non-null fully-qualified URI.

object

The requested value for the property.

Exceptions org.xml.sax.SAXNotRe  cognizedException

If the property value can't be assigned or retrieved.

org.xml.sax.SAXNotSup  portedException

When the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] recognizes the property name but cannot set the requested value.

NullPointerException

When the name parameter is null.

Set the value of a property. The property name is any fully-qualified URI. It is possible for a javax.xml.validation.ValidatorHandler [ Class Valid  atorHandler] to recognize a property name but to be unable to change the current value. Some property values may be immutable or mutable only in specific contexts, such as before, during, or after a validation. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]s are not required to recognize setting any specific property names.

Method setResourceResolver(LSResourceResolver)

public void abstract setResourceResolver(org.w3c.dom.ls.LSResourceResolver resourceResolver

Parameters resourceResolver

A new resource resolver to be set. This parameter can be null.

Sets the org.w3c.dom.ls.LSResourceResolver to customize resource resolution while in a validation episode. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] uses a org.w3c.dom.ls.LSResourceResolver when it needs to locate external resources while a validation, although exactly what constitutes "locating external resources" is up to each schema language. When the org.w3c.dom.ls.LSResourceResolver is null, the implementation will behave as if the following org.w3c.dom.ls.LSResourceResolver is set:

class DumbLSResourceResolver implements org.w3c.dom.ls.LSResourceResolver { public org.w3c.dom.ls.LSInput resolveResource( String publicId, String systemId, String baseURI) {

187

Final 1.0.0

Package javax.xml.validation

return null; // always return null } }

If a org.w3c.dom.ls.LSResourceResolver throws a java.lang.RuntimeException (or instances of its derived classes), then the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] will abort the parsing and the caller of the validate method will receive the same java.lang.RuntimeException. When a new javax.xml.validation.Validat  orHandler [ Class ValidatorHandler] object is created, initially this field is set to null.

188

Final 1.0.0

Chapter 15. Package javax.xml.datatype XML/Java Type Mappings. javax.xml.datatypeAPI provides XML/Java type mappings. The following XML standards apply: •

W3C XML Schema 1.0 Part 2, Section 3.2.7-14 [http://www.w3.org/TR/xmlschema-2/#dateTime]



XQuery 1.0 and XPath 2.0 Data [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]



XQuery 1.0 and XPath 2.0 Data Model, [http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration]

Model,

W3C XML Schema Data Type

Java Data Type

xs:date

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:dateTime

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:duration

javax.xml.datatype.Duration Duration]

xs:gDay

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:gMonth

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:gMonthDay

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:gYear

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:gYearMonth

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xs:time

javax.xml.datatype.XMLGregorianCal  endar [Class XMLGregorianCalendar]

xdt:dayTimeDuration xdt:yearMonthDuration

[Class

XQuery 1.0 and XPath 2.0 Data Java Data Type Model xdt:dayTimeDuration

javax.xml.datatype.Duration Duration]

[Class

xdt:yearMonthDuration

javax.xml.datatype.Duration Duration]

[Class

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

189

Final 1.0.0

Package javax.xml.datatype



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



Author Jeff Suttor [mailto:[email protected]]



See W3C XML Schema 1.0 Part 2, Section 3.2.7-14 [http://www.w3.org/TR/xmlschema-2/#dateTime]



See XQuery 1.0 and XPath 2.0 Data [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]



See XQuery 1.0 and X Pa t h 2.0 Data [http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration]



Since 1.5

Model, Model,

Class DatatypeConstants Utility class to contain basic Datatype values as constants.

Synopsis final DatatypeConstants { } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.2.2.1 $, $Date: 2004/04/28 23:12:57 $

190

Final 1.0.0

x d t : d a y Ti m e D u r a t i o n xdt:yearMonthDuration

Package javax.xml.datatype

Since

1.5

Inheritance Path java.lang.Object | javax.xml.datatype.DatatypeConstants

Members Field APRIL   static int APRIL ; Value for fourth month of year.

Field AUGUST   static int AUGUST ; Value for eighth month of year.

Field DATE   static javax.xml.namespace.QName DATE ; Fully qualified name for W3C XML Schema 1.0 datatype date.

Field DATETIME   static javax.xml.namespace.QName DATETIME ; Fully qualified name for W3C XML Schema 1.0 datatype dateTime.

Field DAYS   static javax.xml.datatype.DatatypeConstants.Field DAYS ; A constant that represents the days field.

Field DECEMBER   static int DECEMBER ; Value for twelve month of year.

Field DURATION   static javax.xml.namespace.QName DURATION ; Fully qualified name for W3C XML Schema datatype duration.

191

Final 1.0.0

Package javax.xml.datatype

Field DURATION_DAYTIME   static javax.xml.namespace.QName DURATION_DAYTIME ; Fully qualified name for XQuery 1.0 and XPath 2.0 datatype dayTimeDuration.

Field DURATION_YEARMONTH   static javax.xml.namespace.QName DURATION_YEARMONTH ; Fully qualified name for XQuery 1.0 and XPath 2.0 datatype yearMonthDuration.

Field EQUAL   static int EQUAL ; Comparison result.

Field FEBRUARY   static int FEBRUARY ; Value for second month of year.

Field FIELD_UNDEFINED   static int FIELD_UNDEFINED ; Designation that an "int" field is not set.

Field GDAY   static javax.xml.namespace.QName GDAY ; Fully qualified name for W3C XML Schema 1.0 datatype gDay.

Field GMONTH   static javax.xml.namespace.QName GMONTH ; Fully qualified name for W3C XML Schema 1.0 datatype gMonth.

Field GMONTHDAY   static javax.xml.namespace.QName GMONTHDAY ; Fully qualified name for W3C XML Schema 1.0 datatype gMonthDay.

Field GREATER   static int GREATER ; Comparison result.

192

Final 1.0.0

Package javax.xml.datatype

Field GYEAR   static javax.xml.namespace.QName GYEAR ; Fully qualified name for W3C XML Schema 1.0 datatype gYear.

Field GYEARMONTH   static javax.xml.namespace.QName GYEARMONTH ; Fully qualified name for W3C XML Schema 1.0 datatype gYearMonth.

Field HOURS   static javax.xml.datatype.DatatypeConstants.Field HOURS ; A constant that represents the hours field.

Field INDETERMINATE   static int INDETERMINATE ; Comparison result.

Field JANUARY   static int JANUARY ; Value for first month of year.

Field JULY   static int JULY ; Value for seventh month of year.

Field JUNE   static int JUNE ; Value for sixth month of year.

Field LESSER   static int LESSER ; Comparison result.

Field MARCH   static int MARCH ; Value for third month of year.

193

Final 1.0.0

Package javax.xml.datatype

Field MAX_TIMEZONE_OFFSET   static int MAX_TIMEZONE_OFFSET ; W3C XML Schema max timezone offset is -14:00. Zone offset is in minutes.

Field MAY   static int MAY ; Value for fifth month of year.

Field MIN_TIMEZONE_OFFSET   static int MIN_TIMEZONE_OFFSET ; W3C XML Schema min timezone offset is +14:00. Zone offset is in minutes.

Field MINUTES   static javax.xml.datatype.DatatypeConstants.Field MINUTES ; A constant that represents the minutes field.

Field MONTHS   static javax.xml.datatype.DatatypeConstants.Field MONTHS ; A constant that represents the months field.

Field NOVEMBER   static int NOVEMBER ; Value for eleven month of year.

Field OCTOBER   static int OCTOBER ; Value for tenth month of year.

Field SECONDS   static javax.xml.datatype.DatatypeConstants.Field SECONDS ; A constant that represents the seconds field.

Field SEPTEMBER   static int SEPTEMBER ; Value for ninth month of year.

194

Final 1.0.0

Package javax.xml.datatype

Field TIME   static javax.xml.namespace.QName TIME ; Fully qualified name for W3C XML Schema 1.0 datatype time.

Field YEARS   static javax.xml.datatype.DatatypeConstants.Field YEARS ; A constant that represents the years field.

Class DatatypeConstants.Field Type-safe enum class that represents six fields of the javax.xml.datatype.Duration [ Class Duration] class.

Synopsis static DatatypeConstants.Field { public String toString(); public int getId(); } Inheritance Path java.lang.Object | javax.xml.datatype.DatatypeConstants.Field

Members Method getId() public int getId(); Get id of this Field.

Method toString() public String toString(); Returns a field name in English. This method is intended to be used for debugging/diagnosis and not for display to end-users.

Class DatatypeFactory Factory that creates new javax.xml.datatype Objects that map XML to/from Java Objects.

195

Final 1.0.0

Package javax.xml.datatype

javax.xml.datatype.DatatypeFactory.newInstance [ Method newInstance()] is used to create a new DatatypeFact  ory195. The following implementation resolution mechanisms are used in the following order: 1.

If the system property specified by javax.xml.datatype.DatatypeFactory.DATATYPEFACTORY_PROPERTY [ Field DATATYPEFACTORY_PROPERTY], " javax.xml.datatype.DatatypeFactory", exists, a class with the name of the property's value is instantiated. Any Exception thrown during the instantiation process is wrapped as a javax.xml.datatype.DatatypeConfigurationException [ Exception DatatypeConfigurationException].

2.

If the file ${JAVA_HOME}/lib/jaxp.properties exists, it is loaded in a java.util.Properties Object. The Prop  erties Object is then queried for the property as documented in the prior step and processed as documented in the prior step.

3.

The services resolution mechanism is used, e.g. META-INF/services/java.xml.datatype.Data  typeFactory. Any Exception thrown during the instantiation process is wrapped as a javax.xml.datatype.Data  typeConfigurationException [ Exception DatatypeConfigurationException].

4.

The final mechanism is to attempt to instantiate the Class specified by javax.xml.datatype.DatatypeFactory.DATA  TYPEFACTORY_IMPLEMENTATION_CLASS [ Field DATATYPEFACTORY_IMPLEMENTATION_CLASS], " javax.xml.datatype.DatatypeFactoryImpl". Any Exception thrown during the instantiation process is wrapped as a javax.xml.datatype.DatatypeConfigurationException [ Exception DatatypeConfigurationException].

Synopsis public DatatypeFactory { protected DatatypeFactory(); static DatatypeFactory newInstance()     throws DatatypeConfigurationException; public Duration abstract newDuration(java.lang.String lexicalRepresentation); public Duration abstract newDuration(long durationInMilliSeconds); public Duration abstract newDuration(boolean isPositive,                                        java.math.BigInteger years,                                        java.math.BigInteger months,                                        java.math.BigInteger days,                                        java.math.BigInteger hours,                                        java.math.BigInteger minutes,                                        java.math.BigDecimal seconds); public Duration newDuration(boolean isPositive,                               int years,                               int months,                               int days,                               int hours,                               int minutes,                               int seconds); public Duration newDurationDayTime(java.lang.String lexicalRepresentation); public Duration newDurationDayTime(long durationInMilliseconds);

196

Final 1.0.0

Package javax.xml.datatype

public Duration newDurationDayTime(boolean isPositive,                                      java.math.BigInteger day,                                      java.math.BigInteger hour,                                      java.math.BigInteger minute,                                      java.math.BigInteger second); public Duration newDurationDayTime(boolean isPositive,                                      int day,                                      int hour,                                      int minute,                                      int second); public Duration newDurationYearMonth(java.lang.String lexicalRepresentation); public Duration newDurationYearMonth(long durationInMilliseconds); public Duration newDurationYearMonth(boolean isPositive,                                        java.math.BigInteger year,                                        java.math.BigInteger month); public Duration newDurationYearMonth(boolean isPositive,                                        int year,                                        int month); public XMLGregorianCalendar abstract newXMLGregorianCalendar();

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.lang.String lexicalRepres

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.util.GregorianCalendar ca

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.math.BigInteger year,                                                                int month,                                                                int day,                                                                int hour,                                                                int minute,                                                                int second,                                                                java.math.BigDecimal fractio                                                                int timezone); public XMLGregorianCalendar newXMLGregorianCalendar(int year,                                                       int month,                                                       int day,                                                       int hour,                                                       int minute,                                                       int second,                                                       int millisecond,                                                       int timezone); public XMLGregorianCalendar newXMLGregorianCalendarDate(int year,                                                           int month,                                                           int day,                                                           int timezone); public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                           int minutes,

197

Final 1.0.0

Package javax.xml.datatype

                                                          int seconds,                                                           int timezone);

public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                           int minutes,                                                           int seconds,                                                           java.math.BigDecimal fractionalSe                                                           int timezone); public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                           int minutes,                                                           int seconds,                                                           int milliseconds,                                                           int timezone); } Author

Joseph Fialli [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.1.6.2.4.3 $, $Date: 2004/06/18 08:40:14 $

Since

1.5

Inheritance Path java.lang.Object | javax.xml.datatype.DatatypeFactory

Members Constructor DatatypeFactory() protected DatatypeFactory(); Protected constructor to prevent instaniation outside of package. Use javax.xml.datatype.DatatypeFactory.newInstance [ Method newInstance()] to create a DatatypeFactory195.

Field DATATYPEFACTORY_IMPLEMENTATION_CLASS   static java.lang.String DATATYPEFACTORY_IMPLEMENTATION_CLASS ; Default implementation class name as defined in JSR 206: Java(TM) API for XML Processing (JAXP) 1.3. Default value is org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl.

Field DATATYPEFACTORY_PROPERTY   static java.lang.String DATATYPEFACTORY_PROPERTY ; Default property name as defined in JSR 206: Java(TM) API for XML Processing (JAXP) 1.3. Default value is javax.xml.datatype.DatatypeFactory.

198

Final 1.0.0

Package javax.xml.datatype

Method newDuration(boolean, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigDecimal) public Duration abstract newDuration(boolean isPositive,                                        java.math.BigInteger years,                                        java.math.BigInteger months,                                        java.math.BigInteger days,                                        java.math.BigInteger hours,                                        java.math.BigInteger minutes,                                        java.math.BigDecimal seconds);

Parameters isPositive

Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.

years

of this Duration213

months

of this Duration213

days

of this Duration213

hours

of this Duration213

minutes

of this Duration213

seconds

of this Duration213

returns

New Duration213 created from the specified values.

Exceptions IllegalArgumentException

If values are not a valid representation of a Duration213.

UnsupportedOperationEx  ception

If implementation cannot support requested values.

Obtain a new instance of a Duration213 specifying the Duration213 as isPositive, years, months, days, hours, minutes, seconds. The XML Schema specification states that values can be of an arbitrary size. Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will be thrown with a message indicating implementation limits if implementation capacities are exceeded. A null value indicates that field isnot set.

Method newDuration(boolean, int, int, int, int, int, int) public Duration newDuration(boolean isPositive,                               int years,                               int months,                               int days,                               int hours,

199

Final 1.0.0

Package javax.xml.datatype

                              int minutes,                               int seconds);

Parameters isPositive

Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.

years

of this Duration213

months

of this Duration213

days

of this Duration213

hours

of this Duration213

minutes

of this Duration213

seconds

of this Duration213

returns

New Duration213 created from the specified values.

Exceptions IllegalArgumentException See Also

If values are not a valid representation of a Duration213.

javax.xml.datatype.DatatypeFactory.newDuration [Method newDuration(boolean, java.math.Bi  gInteger, java.math.BigInteger, java.math.BigInteger, java.math.BigInteger, java.math.BigInteger, java.math.BigDecimal)]

Obtain a new instance of a Duration213 specifying the Duration213 as isPositive, years, months, days, hours, minutes, seconds. A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newDuration(long) public Duration abstract newDuration(long durationInMilliSeconds);

Parameters durationInMilliSeconds

Duration in milliseconds to create.

returns

New Duration213 representing durationInMilliSeconds.

Obtain a new instance of a Duration213 specifying the Duration213 as milliseconds. XML Schema Part 2: Datatypes, 3.2.6 duration, defines duration as: duration represents a duration of time. The value space of duration is a six-dimensional space where the coordinates designate the Gregorian year, month, day, hour, minute, and second components defined in Section 5.5.3.2 of [ISO 8601], respectively. These components are ordered in their signi  ficance by their order of appearance i.e. as year, month, day, hour, minute, and second.

200

Final 1.0.0

Package javax.xml.datatype

All six values are set by computing their values from the specified milliseconds and are availabe using the get methods of the created javax.xml.datatype.Duration [ Class Duration]. The values conform to and are defined by: •

ISO 8601:2000(E) Section 5.5.3.2 Alternative format



W3C XML Schema 1.0 Part 2, Appendix [http://www.w3.org/TR/xmlschema-2/#isoformats]



javax.xml.datatype.XMLGregorianCalendar [ Class XMLGregorianCalendar] Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation

D,

ISO

8601

Date

and

Time

Formats

The default start instance is defined by java.util.GregorianCalendar's use of the start of the epoch: i.e., java.util.Cal  endar.YEAR = 1970, java.util.Calendar.MONTH = java.util.Calendar.JANUARY, java.util.Calendar.DATE = 1, etc. This is important as there are variations in the Gregorian Calendar, e.g. leap years have different days in the month = java.util.Calendar.FEBRUARY so the result of javax.xml.datatype.Duration.getMonths [ Method getMonths()] and javax.xml.datatype.Duration.getDays [ Method getDays()] can be influenced.

Method newDuration(String) public Duration abstract newDuration(java.lang.String lexicalRepresentation);

Parameters lexicalRepresentation

String representation of a Duration213.

returns

New Duration213 created from parsing the lexicalRepresentation.

Exceptions IllegalArgumentException

If lexicalRepresentation is not a valid representation of a Duration213.

UnsupportedOperationEx  ception

If implementation cannot support requested values.

NullPointerException

if lexicalRepresentation is null.

Obtain a new instance of a Duration213 specifying the Duration213 as its string representation, "PnYnMnDTnHnMnS", as defined in XML Schema 1.0 section 3.2.6.1. XML Schema Part 2: Datatypes, 3.2.6 duration, defines duration as: duration represents a duration of time. The value space of duration is a six-dimensional space where the coordinates designate the Gregorian year, month, day, hour, minute, and second components defined in Section 5.5.3.2 of [ISO 8601], respectively. These components are ordered in their signi  ficance by their order of appearance i.e. as year, month, day, hour, minute, and second. All six values are set and availabe from the created javax.xml.datatype.Duration [ Class Duration] The XML Schema specification states that values can be of an arbitrary size. Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will be thrown with a message indicating implementation limits if implementation capacities are exceeded.

201

Final 1.0.0

Package javax.xml.datatype

Method newDurationDayTime(boolean, BigInteger, BigInteger, BigInteger, BigInteger) public Duration newDurationDayTime(boolean isPositive,                                      java.math.BigInteger day,                                      java.math.BigInteger hour,                                      java.math.BigInteger minute,                                      java.math.BigInteger second);

Parameters isPositive

Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.

day

Day of Duration213.

hour

Hour of Duration213.

minute

Minute of Duration213.

second

Second of Duration213.

returns

New Duration213 created with the specified day, hour, minute and second.

Exceptions IllegalArgumentException

If any values would create an invalid Duration213.

UnsupportedOperationEx  ception

If implementation cannot support requested values.

Create a Duration213 of type xdt:dayTimeDuration using the specified day, hour, minute and second as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]. The datatype xdt:dayTimeDuration is a subtype of xs:duration whose lexical representation contains only day, hour, minute, and second components. This datatype resides in the namespace ht  tp://www.w3.org/2003/11/xpath-datatypes. The XML Schema specification states that values can be of an arbitrary size. Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will be thrown with a message indicating implementation limits if implementation capacities are exceeded. A null value indicates that field isnot set.

Method newDurationDayTime(boolean, int, int, int, int) public Duration newDurationDayTime(boolean isPositive,                                      int day,                                      int hour,                                      int minute,                                      int second);

202

Final 1.0.0

Package javax.xml.datatype

Parameters isPositive

Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.

day

Day of Duration213.

hour

Hour of Duration213.

minute

Minute of Duration213.

second

Second of Duration213.

returns

New Duration213 created with the specified day, hour, minute and second.

Exceptions IllegalArgumentException

If any values would create an invalid Duration213.

Create a Duration213 of type xdt:dayTimeDuration using the specified day, hour, minute and second as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]. The datatype xdt:dayTimeDuration is a subtype of xs:duration whose lexical representation contains only day, hour, minute, and second components. This datatype resides in the namespace ht  tp://www.w3.org/2003/11/xpath-datatypes. A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newDurationDayTime(long) public Duration newDurationDayTime(long durationInMilliseconds);

Parameters durationInMilliseconds

Milliseconds of Duration213 to create.

returns

New Duration213 created with the specified durationInMilliseconds.

See Also

XQuery 1.0 and XPath 2.0 Data Model, [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]

xdt:dayTimeDuration

Create a Duration213 of type xdt:dayTimeDuration using the specified milliseconds as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]. The datatype xdt:dayTimeDuration is a subtype of xs:duration whose lexical representation contains only day, hour, minute, and second components. This datatype resides in the namespace ht  tp://www.w3.org/2003/11/xpath-datatypes. All four values are set by computing their values from the specified milliseconds and are availabe using the get methods of the created javax.xml.datatype.Duration [ Class Duration]. The values conform to and are defined by: •

ISO 8601:2000(E) Section 5.5.3.2 Alternative format

203

Final 1.0.0

Package javax.xml.datatype



W3C XML Schema 1.0 Part 2, Appendix [http://www.w3.org/TR/xmlschema-2/#isoformats]

D,

ISO

8601

Date

and

Time

Formats



javax.xml.datatype.XMLGregorianCalendar [ Class XMLGregorianCalendar] Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation

The default start instance is defined by java.util.GregorianCalendar's use of the start of the epoch: i.e., java.util.Cal  endar.YEAR = 1970, java.util.Calendar.MONTH = java.util.Calendar.JANUARY, java.util.Calendar.DATE = 1, etc. This is important as there are variations in the Gregorian Calendar, e.g. leap years have different days in the month = java.util.Calendar.FEBRUARY so the result of javax.xml.datatype.Duration.getDays [ Method getDays()] can be influ  enced. Any remaining milliseconds after determining the day, hour, minute and second are discarded.

Method newDurationDayTime(String) public Duration newDurationDayTime(java.lang.String lexicalRepresentation);

Parameters lexicalRepresentation

Lexical representation of a duration.

returns

New Duration213 created using the specified lexicalRepresentation.

Exceptions IllegalArgumentException

If the given string does not conform to the aforementioned specification.

UnsupportedOperationEx  ception

If implementation cannot support requested values.

NullPointerException

If lexicalRepresentation is null.

Create a Duration213 of type xdt:dayTimeDuration by parsing its String representation, " PnDTnHnMnS", XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration [http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]. The datatype xdt:dayTimeDuration is a subtype of xs:duration whose lexical representation contains only day, hour, minute, and second components. This datatype resides in the namespace ht  tp://www.w3.org/2003/11/xpath-datatypes. All four values are set and availabe from the created javax.xml.datatype.Duration [ Class Duration] The XML Schema specification states that values can be of an arbitrary size. Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will be thrown with a message indicating implementation limits if implementation capacities are exceeded.

Method newDurationYearMonth(boolean, BigInteger, BigInteger) public Duration newDurationYearMonth(boolean isPositive,                                        java.math.BigInteger year,                                        java.math.BigInteger month);

204

Final 1.0.0

Package javax.xml.datatype

Parameters isPositive

Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.

year

Year of Duration213.

month

Month of Duration213.

returns

New Duration213 created using the specified year and month.

Exceptions IllegalArgumentException

If any values would create an invalid Duration213.

UnsupportedOperationEx  ception

If implementation cannot support requested values.

Create a Duration213 of type xdt:yearMonthDuration using the specified year and month as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration [http://www.w3.org/TR/xpath-datamodel#dt-yearMonthyDuration]. The XML Schema specification states that values can be of an arbitrary size. Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will be thrown with a message indicating implementation limits if implementation capacities are exceeded. A null value indicates that field isnot set.

Method newDurationYearMonth(boolean, int, int) public Duration newDurationYearMonth(boolean isPositive,                                        int year,                                        int month);

Parameters isPositive

Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.

year

Year of Duration213.

month

Month of Duration213.

returns

New Duration213 created using the specified year and month.

Exceptions IllegalArgumentException

If any values would create an invalid Duration213.

Create a Duration213 of type xdt:yearMonthDuration using the specified year and month as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration [http://www.w3.org/TR/xpath-datamodel#dt-yearMonthyDuration].

205

Final 1.0.0

Package javax.xml.datatype

A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newDurationYearMonth(long) public Duration newDurationYearMonth(long durationInMilliseconds);

Parameters durationInMilliseconds

Milliseconds of Duration213 to create.

returns

New Duration213 created using the specified durationInMilliseconds.

Create a Duration213 of type xdt:yearMonthDuration using the specified milliseconds as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration [http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration]. The datatype xdt:yearMonthDuration is a subtype of xs:duration whose lexical representation contains only year and month components. This datatype resides in the namespace javax.xml.XMLConstants.W3C_XPATH_DATA  TYPE_NS_URI. Both values are set by computing their values from the specified milliseconds and are availabe using the get methods of the created javax.xml.datatype.Duration [ Class Duration]. The values conform to and are defined by: •

ISO 8601:2000(E) Section 5.5.3.2 Alternative format



W3C XML Schema 1.0 Part 2, Appendix [http://www.w3.org/TR/xmlschema-2/#isoformats]



javax.xml.datatype.XMLGregorianCalendar [ Class XMLGregorianCalendar] Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation

D,

ISO

8601

Date

and

Time

Formats

The default start instance is defined by java.util.GregorianCalendar's use of the start of the epoch: i.e., java.util.Cal  endar.YEAR = 1970, java.util.Calendar.MONTH = java.util.Calendar.JANUARY, java.util.Calendar.DATE = 1, etc. This is important as there are variations in the Gregorian Calendar, e.g. leap years have different days in the month = java.util.Calendar.FEBRUARY so the result of javax.xml.datatype.Duration.getMonths [ Method getMonths()] can be influenced. Any remaining milliseconds after determining the year and month are discarded.

Method newDurationYearMonth(String) public Duration newDurationYearMonth(java.lang.String lexicalRepresentation);

Parameters lexicalRepresentation

Lexical representation of a duration.

returns

New Duration213 created using the specified lexicalRepresentation.

Exceptions IllegalArgumentException

If the lexicalRepresentation does not conform to the specification.

206

Final 1.0.0

Package javax.xml.datatype

UnsupportedOperationEx  ception

If implementation cannot support requested values.

NullPointerException

If lexicalRepresentation is null.

Create a Duration213 of type xdt:yearMonthDuration by parsing its String representation, " PnYnM", XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration [http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration]. The datatype xdt:yearMonthDuration is a subtype of xs:duration whose lexical representation contains only year and month components. This datatype resides in the namespace javax.xml.XMLConstants.W3C_XPATH_DATA  TYPE_NS_URI. Both values are set and availabe from the created javax.xml.datatype.Duration [ Class Duration] The XML Schema specification states that values can be of an arbitrary size. Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will be thrown with a message indicating implementation limits if implementation capacities are exceeded.

Method newInstance() static DatatypeFactory newInstance()     throws DatatypeConfigurationException;

Exceptions DatatypeConfigurationEx  ception

If the implementation is not available or cannot be instantiated.

Obtain a new instance of a DatatypeFactory195. The implementation resolution mechanisms are defined [#DatatypeFactory.newInstance] in this Class's documentation.

Method newXMLGregorianCalendar() public XMLGregorianCalendar abstract newXMLGregorianCalendar(); Create a new instance of an XMLGregorianCalendar227. All date/time datatype fields set to javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UN  DEFINED] or null.

Method newXMLGregorianCalendar(BigInteger, int, int, int, int, int, BigDecimal, int)

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.math.BigInteger year,                                                                int month,                                                                int day,                                                                int hour,                                                                int minute,                                                                int second,                                                                java.math.BigDecimal fractio                                                                int timezone);

207

Final 1.0.0

Package javax.xml.datatype

Parameters year

of XMLGregorianCalendar227 to be created.

month

of XMLGregorianCalendar227 to be created.

day

of XMLGregorianCalendar227 to be created.

hour

of XMLGregorianCalendar227 to be created.

minute

of XMLGregorianCalendar227 to be created.

second

of XMLGregorianCalendar227 to be created.

fractionalSecond

of XMLGregorianCalendar227 to be created.

timezone

of XMLGregorianCalendar227 to be created.

returns

XMLGregorianCalendar227 created from specified values.

Exceptions IllegalArgumentException

If any individual parameter's value is outside the maximum value constraint for the field as determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori  anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute an invalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM  LGregorianCalendar.isValid [ Method isValid()].

Constructor allowing for complete value spaces allowed by W3C XML Schema 1.0 recommendation for xsd:dateTime and related builtin datatypes. Note that year parameter supports arbitrarily large numbers and fractionalSecond has infinite precision. A null value indicates that field isnot set.

Method newXMLGregorianCalendar(GregorianCalendar)

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.util.GregorianCalendar ca

Parameters cal

java.util.GregorianCalendar used to create XMLGregorianCalendar227

returns

XMLGregorianCalendar227 created from java.util.GregorianCalendar

Exceptions NullPointerException

If cal is null.

Create an XMLGregorianCalendar227 from a java.util.GregorianCalendar.

208

Final 1.0.0

Package javax.xml.datatype

Field by Field Conversion from java.util.GregorianCalendar to an javax.xml.datatype.XMLGregorianCalendar [Class XMLGregorianCalendar] java.util.GregorianCalen  javax.xml.datatype.XML  dar field GregorianCalendar field ERA == GregorianCalen  javax.xml.datatype.XMLGregorianCal  endar.setYear [Method setYear(int)] dar.BC ? -YEAR : YEAR MONTH + 1

javax.xml.datatype.XMLGregorianCal  endar.setMonth [Method set  Month(int)]

DAY_OF_MONTH

javax.xml.datatype.XMLGregorianCal  endar.setDay [Method setDay(int)]

HOUR_OF_DAY, MINUTE, javax.xml.datatype.XMLGregorianCal  endar.setTime [Method setTime(int, SECOND, MILLISECOND int, int, java.math.BigDecimal)] (ZONE_OFFSET + DST_OFFSET) javax.xml.datatype.XMLGregorianCal  endar.setTimezone [Method set  / (60*1000)(in minutes) Timezone(int)]* *conversion loss of information. It is not possible to represent a java.util.GregorianCalendar daylight savings timezone id in the XML Schema 1.0 date/time datatype representation. To compute the return value's TimeZone field, •

when this.getTimezone() != FIELD_UNDEFINED, create a java.util.TimeZone with a custom timezone id using the this.getTimezone().



else use the GregorianCalendar default timezone value for the host is defined as specified by java.util.TimeZone.getDefault().

Method newXMLGregorianCalendar(int, int, int, int, int, int, int, int) public XMLGregorianCalendar newXMLGregorianCalendar(int year,                                                       int month,                                                       int day,                                                       int hour,                                                       int minute,                                                       int second,                                                       int millisecond,                                                       int timezone);

Parameters year

of XMLGregorianCalendar227 to be created.

month

of XMLGregorianCalendar227 to be created.

day

of XMLGregorianCalendar227 to be created.

hour

of XMLGregorianCalendar227 to be created.

minute

of XMLGregorianCalendar227 to be created.

209

Final 1.0.0

Package javax.xml.datatype

second

of XMLGregorianCalendar227 to be created.

millisecond

of XMLGregorianCalendar227 to be created.

timezone

of XMLGregorianCalendar227 to be created.

returns

XMLGregorianCalendar227 created from specified values.

Exceptions IllegalArgumentException

If any individual parameter's value is outside the maximum value constraint for the field as determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori  anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute an invalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM  LGregorianCalendar.isValid [ Method isValid()].

Constructor of value spaces that a java.util.GregorianCalendar instance would need to convert to an XML  GregorianCalendar227 instance. XMLGregorianCalendar eon and fractionalSecond are set to null A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newXMLGregorianCalendar(String)

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.lang.String lexicalRepres

Parameters lexicalRepresentation

Lexical representation of one the eight XML Schema date/time datatypes.

returns

XMLGregorianCalendar227 created from the lexicalRepresentation.

Exceptions IllegalArgumentException

If the lexicalRepresentation is not a valid XMLGregorianCalendar227.

NullPointerException

If lexicalRepresentation is null.

Create a new XMLGregorianCalendar by parsing the String as a lexical representation. Parsing the lexical string representation is defined in XML Schema 1.0 Part 2, Section 3.2.[7-14].1, Lexical Represent  ation. [http://www.w3.org/TR/xmlschema-2/#dateTime-order] The string representation may not have any leading and trailing whitespaces. The parsing is done field by field so that the following holds for any lexically correct String x:

newXMLGregorianCalendar(x).toXMLFormat().equals(x)

210

Final 1.0.0

Package javax.xml.datatype

Except for the noted lexical/canonical representation mismatches listed in XML Schema 1.0 errata, Section 3.2.7.2 [http://www.w3.org/2001/05/xmlschema-errata#e2-45].

Method newXMLGregorianCalendarDate(int, int, int, int) public XMLGregorianCalendar newXMLGregorianCalendarDate(int year,                                                           int month,                                                           int day,                                                           int timezone);

Parameters year

of XMLGregorianCalendar227 to be created.

month

of XMLGregorianCalendar227 to be created.

day

of XMLGregorianCalendar227 to be created.

timezone

offset in minutes. javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED FIELD_UNDEFINED] indicates optional field is not set.

returns

XMLGregorianCalendar227 created from parameter values.

[

Field

Exceptions IllegalArgumentException

See Also

If any individual parameter's value is outside the maximum value constraint for the field as determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori  anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute an invalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM  LGregorianCalendar.isValid [ Method isValid()].

javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [Field FIELD_UNDEFINED]

Create a Java representation of XML Schema builtin datatype date or g*. For example, an instance of gYear can be created invoking this factory with month and day parameters set to javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newXMLGregorianCalendarTime(int, int, int, BigDecimal, int)

public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                           int minutes,                                                           int seconds,                                                           java.math.BigDecimal fractionalSe                                                           int timezone);

Parameters hours

number of hours

minutes

number of minutes

211

Final 1.0.0

Package javax.xml.datatype

seconds

number of seconds

fractionalSecond

value of null indicates that this optional field is not set.

timezone

offset in minutes. javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] indicates optional field is not set.

returns

XMLGregorianCalendar227 created from parameter values.

Exceptions IllegalArgumentException

See Also

If any individual parameter's value is outside the maximum value constraint for the field as determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori  anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute an invalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM  LGregorianCalendar.isValid [ Method isValid()].

javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [Field FIELD_UNDEFINED]

Create a Java instance of XML Schema builtin datatype time. A null value indicates that field isnot set. A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newXMLGregorianCalendarTime(int, int, int, int) public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                           int minutes,                                                           int seconds,                                                           int timezone);

Parameters hours

number of hours

minutes

number of minutes

seconds

number of seconds

timezone

offset in minutes. javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED FIELD_UNDEFINED] indicates optional field is not set.

returns

XMLGregorianCalendar227 created from parameter values.

[

Field

Exceptions IllegalArgumentException

See Also

If any individual parameter's value is outside the maximum value constraint for the field as determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori  anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute an invalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM  LGregorianCalendar.isValid [ Method isValid()].

javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [Field FIELD_UNDEFINED]

212

Final 1.0.0

Package javax.xml.datatype

Create a Java instance of XML Schema builtin datatype time. A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Method newXMLGregorianCalendarTime(int, int, int, int, int) public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                           int minutes,                                                           int seconds,                                                           int milliseconds,                                                           int timezone);

Parameters hours

number of hours

minutes

number of minutes

seconds

number of seconds

milliseconds

number of milliseconds

timezone

offset in minutes. javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] indicates optional field is not set.

returns

XMLGregorianCalendar227 created from parameter values.

Exceptions IllegalArgumentException

See Also

If any individual parameter's value is outside the maximum value constraint for the field as determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori  anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute an invalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM  LGregorianCalendar.isValid [ Method isValid()].

javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [Field FIELD_UNDEFINED]

Create a Java instance of XML Schema builtin datatype time. A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates that field isnot set.

Class Duration Immutable representation of a time span as defined in the W3C XML Schema 1.0 specification. A Duration object represents a period of Gregorian time, which consists of six fields (years, months, days, hours, minutes, and seconds) plus a sign (+/-) field. The first five fields have non-negative (>=0) integers or null (which represents that the field is not set), and the seconds field has a non-negative decimal or null. A negative sign indicates a negative duration.

213

Final 1.0.0

Package javax.xml.datatype

This class provides a number of methods that make it easy to use for the duration datatype of XML Schema 1.0 with the errata.

Order relationship Duration objects only have partial order, where two values A and B maybe either: 1.

A
2.

A>B (A is longer than B)

3.

A==B (A and B are of the same duration)

4.

A<>B (Comparison between A and B is indeterminate)

* For example, 30 days cannot be meaningfully compared to one month. The javax.xml.datatype.Duration.compare [ Method compare(javax.xml.datatype.Duration)] method implements this relationship. See the javax.xml.datatype.Duration.isLongerThan [ Method isLongerThan(javax.xml.datatype.Duration)] method for details about the order relationship among Duration213 objects.

Operations over Duration This class provides a set of basic arithmetic operations, such as addition, subtraction and multiplication. Because dur  ations don't have total order, an operation could fail for some combinations of operations. For example, you cannot subtract 15 days from 1 month. See the javadoc of those methods for detailed conditions where this could happen. Also, division of a duration by a number is not provided because the Duration213 class can only deal with finite precision decimal numbers. For example, one cannot represent 1 sec divided by 3. However, you could substitute a division by 3 with multiplying by numbers such as 0.3 or 0.333.

Range of allowed values Because some operations of Duration213 rely on java.util.Calendar even though javax.xml.datatype.Duration [ Class Duration] can hold very large or very small values, some of the methods may not work correctly on such Duration213s. The impacted methods document their dependency on java.util.Calendar.

Synopsis public Duration { public Duration(); public QName getXMLSchemaType(); public int abstract getSign(); public int getYears(); public int getMonths();

214

Final 1.0.0

Package javax.xml.datatype

public int getDays(); public int getHours(); public int getMinutes(); public int getSeconds(); public long getTimeInMillis(java.util.Calendar startInstant); public long getTimeInMillis(java.util.Date startInstant); public Number abstract getField(javax.xml.datatype.DatatypeConstants.Field field); public boolean abstract isSet(javax.xml.datatype.DatatypeConstants.Field field); public Duration abstract add(javax.xml.datatype.Duration rhs); public void abstract addTo(java.util.Calendar calendar); public void addTo(java.util.Date date); public Duration subtract(javax.xml.datatype.Duration rhs); public Duration multiply(int factor); public Duration abstract multiply(java.math.BigDecimal factor); public Duration abstract negate(); public Duration abstract normalizeWith(java.util.Calendar startTimeInstant); public int abstract compare(javax.xml.datatype.Duration duration); public boolean isLongerThan(javax.xml.datatype.Duration duration); public boolean isShorterThan(javax.xml.datatype.Duration duration); public boolean equals(java.lang.Object duration); public int abstract hashCode(); public String toString(); } Author

Joseph Fialli [mailto:[email protected]], Kohsuke Kawaguchi [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.36.8.1.4.3 $, $Date: 2004/06/07 06:33:50 $

Since

1.5

See Also

javax.xml.datatype.XMLGregorianCalendar.add [Method add(javax.xml.datatype.Duration)]

Inheritance Path java.lang.Object

215

Final 1.0.0

Package javax.xml.datatype

Inheritance Path | javax.xml.datatype.Duration

Members Method add(Duration) public Duration abstract add(javax.xml.datatype.Duration rhs);

Parameters rhs

Duration213 to add to this Duration213

returns

non-null valid Duration object.

Exceptions NullPointerException

If the rhs parameter is null.

IllegalStateException

If two durations cannot be meaningfully added. For example, adding negative one day to one month causes this exception.

See Also

javax.xml.datatype.Duration.subtract [Method subtract(javax.xml.datatype.Duration)]

Computes a new duration whose value is this+rhs. For example,

"1 day" + "-3 days" = "-2 days" "1 year" + "1 day" = "1 year and 1 day" "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)" "15 hours" + "-3 days" = "-(2 days,9 hours)" "1 year" + "-1 day" = IllegalStateException

Since there's no way to meaningfully subtract 1 day from 1 month, there are cases where the operation fails in java.lang.IllegalStateException. Formally, the computation is defined as follows. Firstly, we can assume that two Duration213s to be added are both positive without losing generality (i.e., (-X)+Y=Y-X, X+(-Y)=X-Y, (-X)+(Y)=-(X+Y)) Addition of two positive Duration213s are simply defined as field by field addition where missing fields are treated as 0. A field of the resulting Duration213 will be unset if and only if respective fields of two input Duration213s are unset. Note that lhs.add(rhs) will be always successful if lhs.signum()*rhs.signum()!=-1 or both of them are normalized.

Method addTo(Calendar) public void abstract addTo(java.util.Calendar calendar);

216

Final 1.0.0

Package javax.xml.datatype

Parameters calendar

A calendar object whose value will be modified.

Exceptions NullPointerException

if the calendar parameter is null.

Adds this duration to a java.util.Calendar object. Calls java.util.Calendar.add in the order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MIL  LISECONDS if those fields are present. Because the java.util.Calendar class uses int to hold values, there are cases where this method won't work correctly (for example if values of fields exceed the range of int.) Also, since this duration class is a Gregorian duration, this method will not work correctly if the given java.util.Calendar object is based on some other calendar systems. Any fractional parts of this Duration213 object beyond milliseconds will be simply ignored. For example, if this duration is "P1.23456S", then 1 is added to SECONDS, 234 is added to MILLISECONDS, and the rest will be unused. Note that because java.util.Calendar.add is using

int , Duration213 with values beyond the range of

int in its fields will cause overflow/underflow to the given java.util.Calendar. javax.xml.datatype.XMLGregorianCalen  dar.add [ Method add(javax.xml.datatype.Duration)] provides the same basic operation as this method while avoiding the overflow/underflow issues.

Method addTo(Date) public void addTo(java.util.Date date);

Parameters date

A date object whose value will be modified.

Exceptions NullPointerException

if the date parameter is null.

Adds this duration to a java.util.Date object. The given date is first converted into a java.util.GregorianCalendar, then the duration is added exactly like the javax.xml.datatype.Duration.addTo [ Method addTo(java.util.Calendar)] method. The updated time instant is then converted back into a java.util.Date object and used to update the given java.util.Date object. This somewhat redundant computation is necessary to unambiguously determine the duration of months and years.

217

Final 1.0.0

Package javax.xml.datatype

Method compare(Duration) public int abstract compare(javax.xml.datatype.Duration duration);

Parameters duration

to compare

returns

the relationship between this Duration213and duration parameter as javax.xml.datatype.Data  typeConstants.LESSER [ Field LESSER], javax.xml.datatype.DatatypeConstants.EQUAL [ Field EQUAL], javax.xml.datatype.DatatypeConstants.GREATER [ Field GREATER] or javax.xml.datatype.DatatypeConstants.INDETERMINATE [ Field INDETERMINATE].

Exceptions UnsupportedOperationEx  ception

If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.

NullPointerException

if duration is null.

See Also

javax.xml.datatype.Duration.isShorterThan [Method isShorterThan(javax.xml.datatype.Duration)], javax.xml.datatype.Duration.isLongerThan [Method isLongerThan(javax.xml.datatype.Duration)]

Partial order relation comparison with this Duration213 instance. Comparison result must be in accordance with W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2, Order relation on duration [http://www.w3.org/TR/xmlschema-2/#duration-order]. Return: •

javax.xml.datatype.DatatypeConstants.LESSER [ Field LESSER] if this Duration213 is shorter than duration parameter



javax.xml.datatype.DatatypeConstants.EQUAL [ Field EQUAL] if this Duration213 is equal to duration parameter



javax.xml.datatype.DatatypeConstants.GREATER [ Field GREATER] if this Duration213 is longer than duration parameter



javax.xml.datatype.DatatypeConstants.INDETERMINATE [ Field INDETERMINATE] if a conclusive partial order relation cannot be determined

Method equals(Object) public boolean equals(java.lang.Object duration);

Parameters duration

A non-null valid Duration213 object.

returns

true if this duration is the same length as duration. false if duration is not a Duration 213 object or its length is different from this duration.

218

Final 1.0.0

Package javax.xml.datatype

Exceptions UnsupportedOperationEx  ception

If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.

NullPointerException

if parameter is null.

See Also

javax.xml.datatype.Duration.compare [Method compare(javax.xml.datatype.Duration)]

Checks if this duration object has the same duration as another Duration213 object. For example, "P1D" (1 day) is equal to "PT24H" (24 hours). Duration X is equal to Y if and only if time instant t+X and t+Y are the same for all the test time instants specified in the section 3.2.6.2 of the XML Schema 1.0 specification. Note that there are cases where two Duration213s are "incomparable" to each other, like one month and 30 days. For example,

!new Duration("P1M").isShorterThan(new Duration("P30D")) !new Duration("P1M").isLongerThan(new Duration("P30D")) !new Duration("P1M").equals(new Duration("P30D"))

Method getDays() public int getDays(); Obtains the value of the DAYS field as an integer value, or 0 if not present. This method works just like javax.xml.datatype.Duration.getYears [ Method getYears()] except that this method works on the DAYS field.

Method getField(DatatypeConstants.Field) public Number abstract getField(javax.xml.datatype.DatatypeConstants.Field field);

Parameters field

one of the six Field constants (YEARS,MONTHS,DAYS,HOURS, MINUTES, or SECONDS.)

returns

If the specified field is present, this method returns a non-null non-negative java.lang.Number object that represents its value. If it is not present, return null. For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method returns a java.math.BigInteger object. For SECONDS, this method returns a java.math.BigDecimal.

Exceptions NullPointerException

If the field is null.

Gets the value of a field. Fields of a duration object may contain arbitrary large value. Therefore this method is designed to return a java.lang.Number object. In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned number will be a non-negative integer. In case of seconds, the returned number may be a non-negative decimal value.

219

Final 1.0.0

Package javax.xml.datatype

Method getHours() public int getHours(); Obtains the value of the HOURS field as an integer value, or 0 if not present. This method works just like javax.xml.datatype.Duration.getYears [ Method getYears()] except that this method works on the HOURS field.

Method getMinutes() public int getMinutes(); Obtains the value of the MINUTES field as an integer value, or 0 if not present. This method works just like javax.xml.datatype.Duration.getYears [ Method getYears()] except that this method works on the MINUTES field.

Method getMonths() public int getMonths(); Obtains the value of the MONTHS field as an integer value, or 0 if not present. This method works just like javax.xml.datatype.Duration.getYears [ Method getYears()] except that this method works on the MONTHS field.

Method getSeconds() public int getSeconds(); Obtains the value of the SECONDS field as an integer value, or 0 if not present. This method works just like javax.xml.datatype.Duration.getYears [ Method getYears()] except that this method works on the SECONDS field.

Method getSign() public int abstract getSign(); Returns the sign of this duration in -1,0, or 1.

Method getTimeInMillis(Calendar) public long getTimeInMillis(java.util.Calendar startInstant);

Parameters startInstant

The length of a month/year varies. The startInstant is used to disambiguate this variance. Specifically, this method returns the difference between startInstant and startInstant+duration

returns

milliseconds between startInstant and startInstant plus this Duration213

Exceptions NullPointerException

if startInstant parameter is null.

Returns the length of the duration in milli-seconds. If the seconds field carries more digits than milli-second order, those will be simply discarded (or in other words, rounded to zero.) For example, for any Calendar value x,

220

Final 1.0.0

Package javax.xml.datatype

new Duration("PT10.00099S").getTimeInMills(x) == 10000. new Duration("-PT10.00099S").getTimeInMills(x) == -10000.

Note that this method uses the javax.xml.datatype.Duration.addTo [ Method addTo(java.util.Calendar)] method, which may work incorrectly with Duration213 objects with very large values in its fields. See the javax.xml.datatype.Dura  tion.addTo [ Method addTo(java.util.Calendar)] method for details.

Method getTimeInMillis(Date) public long getTimeInMillis(java.util.Date startInstant);

Parameters startInstant

The length of a month/year varies. The startInstant is used to disambiguate this variance. Specifically, this method returns the difference between startInstant and startInstant+duration.

returns

milliseconds between startInstant and startInstant plus this Duration213

Exceptions NullPointerException See Also

If the startInstant parameter is null.

javax.xml.datatype.Duration.getTimeInMillis [Method getTimeInMillis(java.util.Calendar)]

Returns the length of the duration in milli-seconds. If the seconds field carries more digits than milli-second order, those will be simply discarded (or in other words, rounded to zero.) For example, for any Date value x,

new Duration("PT10.00099S").getTimeInMills(x) == 10000. new Duration("-PT10.00099S").getTimeInMills(x) == -10000.

Note that this method uses the javax.xml.datatype.Duration.addTo [ Method addTo(java.util.Date)] method, which may work incorrectly with Duration213 objects with very large values in its fields. See the javax.xml.datatype.Dura  tion.addTo [ Method addTo(java.util.Date)] method for details.

Method getXMLSchemaType() public QName getXMLSchemaType();

221

Final 1.0.0

Package javax.xml.datatype

Exceptions IllegalStateException

If the combination of set fields does not match one of the XML Schema date/time data  types.

Return the name of the XML Schema date/time type that this instance maps to. Type is computed based on fields that are set, i.e. javax.xml.datatype.Duration.isSet [ Method isSet(javax.xml.datatype.DatatypeConstants.Field)] == true. Required fields for XML Schema 1.0 Date/Time Datatypes.(timezone is optional for all date/time datatypes) Datatype

year

javax.xml.data  X type.Data  typeCon  stants.DURA  TION [Field DURATION]

month

day

hour

minute

second

X

X

X

X

X

X

X

X

X

javax.xml.data  type.Data  typeCon  stants.DURA  T I O N _ DAY   TIME [Field D U R A   T I O N _ DAY   TIME] javax.xml.data  X type.Data  typeCon  stants.DURA  TION_YEAR  MONTH [Field D U R A   TION_YEAR  MONTH]

X

Method getYears() public int getYears(); Get the years value of this Duration213 as an int or 0 if not present. getYears() is a convenience method for getField(DatatypeConstants.YEARS) [ Method getField(javax.xml.data  type.DatatypeConstants.Field)]. As the return value is an int, an incorrect value will be returned for Duration213s with years that go beyond the range of an int. Use getField(DatatypeConstants.YEARS) [ Method getField(javax.xml.datatype.DatatypeCon  stants.Field)] to avoid possible loss of precision.

Method hashCode() public int abstract hashCode();

222

Final 1.0.0

Package javax.xml.datatype

See Also

java.lang.Object.hashCode

Returns a hash code consistent with the definition of the equals method.

Method isLongerThan(Duration) public boolean isLongerThan(javax.xml.datatype.Duration duration);

Parameters duration

Duration213 to test this Duration213 against.

returns

true if the duration represented by this object is longer than the given duration. false otherwise.

Exceptions UnsupportedOperationEx  ception

If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.

NullPointerException

If duration is null.

See Also

javax.xml.datatype.Duration.isShorterThan [Method isShorterThan(javax.xml.datatype.Duration)], javax.xml.datatype.Duration.compare [Method compare(javax.xml.datatype.Duration)]

Checks if this duration object is strictly longer than another Duration213 object. Duration X is "longer" than Y if and only if X>Y as defined in the section 3.2.6.2 of the XML Schema 1.0 specification. For example, "P1D" (one day) > "PT12H" (12 hours) and "P2Y" (two years) > "P23M" (23 months).

Method isSet(DatatypeConstants.Field) public boolean abstract isSet(javax.xml.datatype.DatatypeConstants.Field field);

Parameters field

one of the six Field constants (YEARS,MONTHS,DAYS,HOURS, MINUTES, or SECONDS.)

returns

true if the field is present. false if not.

Exceptions NullPointerException

If the field parameter is null.

Checks if a field is set. A field of a duration object may or may not be present. This method can be used to test if a field is present.

Method isShorterThan(Duration) public boolean isShorterThan(javax.xml.datatype.Duration duration);

223

Final 1.0.0

Package javax.xml.datatype

Parameters duration

Duration213 to test this Duration213 against.

returns

true if duration parameter is shorter than this Duration213, else false.

Exceptions UnsupportedOperationEx  ception

If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.

NullPointerException

if duration is null.

See Also

javax.xml.datatype.Duration.isLongerThan [Method isLongerThan(javax.xml.datatype.Duration)], javax.xml.datatype.Duration.compare [Method compare(javax.xml.datatype.Duration)]

Checks if this duration object is strictly shorter than another Duration213 object.

Method multiply(BigDecimal) public Duration abstract multiply(java.math.BigDecimal factor);

Parameters factor

to multiply by

returns

returns a non-null valid Duration213 object

Exceptions IllegalStateException

if operation produces fraction in the months field.

NullPointerException

if the factor parameter is null.

Computes a new duration whose value is factor times longer than the value of this duration. For example,

"P1M" (1 month) * "12" = "P12M" (12 months) "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds) "P1M" (1 month) * "1.5" = IllegalStateException

Since the Duration213 class is immutable, this method doesn't change the value of this object. It simply computes a new Duration object and returns it. The operation will be performed field by field with the precision of java.math.BigDecimal. Since all the fields except seconds are restricted to hold integers, any fraction produced by the computation will be carried down toward the next lower unit. For example, if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day, which will be carried down to "PT12H" (12 hours). When fractions of month cannot be mean  ingfully carried down to days, or year to months, this will cause an java.lang.IllegalStateException to be thrown. For example if you multiple one month by 0.5. To avoid java.lang.IllegalStateException, use the javax.xml.datatype.Dur  ation.normalizeWith [ Method normalizeWith(java.util.Calendar)] method to remove the years and months fields.

224

Final 1.0.0

Package javax.xml.datatype

Method multiply(int) public Duration multiply(int factor);

Parameters factor

Factor times longer of new Duration213 to create.

returns

New Duration213 that is factortimes longer than this Duration213.

See Also

javax.xml.datatype.Duration.multiply [Method multiply(java.math.BigDecimal)]

Computes a new duration whose value is factor times longer than the value of this duration. This method is provided for the convenience. It is functionally equivalent to the following code:

multiply(new BigDecimal(String.valueOf(factor)))

Method negate() public Duration abstract negate(); Returns a new Duration213 object whose value is -this. Since the Duration213 class is immutable, this method doesn't change the value of this object. It simply computes a new Duration object and returns it.

Method normalizeWith(Calendar) public Duration abstract normalizeWith(java.util.Calendar startTimeInstant);

Parameters startTimeInstant

Calendar reference point.

returns

Duration213 of years and months of this Duration213 as days.

Exceptions NullPointerException

If the startTimeInstant parameter is null.

Converts the years and months fields into the days field by using a specific time instant as the reference point. For example, duration of one month normalizes to 31 days given the start time instance "July 8th 2003, 17:40:32". Formally, the computation is done as follows: 1.

the given Calendar object is cloned

2.

the years, months and days fields will be added to the java.util.Calendar object by using the java.util.Calendar.add method

225

Final 1.0.0

Package javax.xml.datatype

3.

the difference between the two Calendars in computed in milliseconds and converted to days, if a remainder occurs due to Daylight Savings Time, it is discarded

4.

the computed days, along with the hours, minutes and seconds fields of this duration object is used to construct a new Duration object.

Note that since the Calendar class uses int to hold the value of year and month, this method may produce an unexpected result if this duration object holds a very large value in the years or months fields.

Method subtract(Duration) public Duration subtract(javax.xml.datatype.Duration rhs);

Parameters rhs

Duration213 to subtract from this Duration213.

returns

New Duration213 created from subtracting rhs from this Duration213.

Exceptions IllegalStateException

If two durations cannot be meaningfully subtracted. For example, subtracting one day from one month causes this exception.

NullPointerException

If the rhs parameter is null.

See Also

javax.xml.datatype.Duration.add [Method add(javax.xml.datatype.Duration)]

Computes a new duration whose value is this-rhs. For example:

"1 day" - "-3 days" = "4 days" "1 year" - "1 day" = IllegalStateException "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)" "15 hours" - "-3 days" = "3 days and 15 hours" "1 year" - "-1 day" = "1 year and 1 day"

Since there's no way to meaningfully subtract 1 day from 1 month, there are cases where the operation fails in java.lang.IllegalStateException.Formally the computation is defined as follows. First, we can assume that two Dura  tion213s are both positive without losing generality. (i.e., (-X)-Y=-(X+Y), X-(-Y)=X+Y, (-X)-(-Y)=-(XY))Then two durations are subtracted field by field. If the sign of any non-zero field

F is different from the sign of the most significant field, 1 (if

F is negative) or -1 (otherwise) will be borrowed from the next bigger unit of

226

Final 1.0.0

Package javax.xml.datatype

F .This process is repeated until all the non-zero fields have the same sign.If a borrow occurs in the days field (in other words, if the computation needs to borrow 1 or -1 month to compensate days), then the computation fails by throwing an java.lang.IllegalStateException.

Method toString() public String toString(); Returns a String representation of this Duration213 Object. The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the equivalent Duration213 Object by javax.xml.datatype.DatatypeFactory.newDuration [ Method newDuration(java.lang.String)]. Formally, the following holds for any Duration213 Object x:

new Duration(x.toString()).equals(x)

Class XMLGregorianCalendar Representation for W3C XML Schema 1.0 date/time datatypes. Specifically, these date/time datatypes are dateTime [#DATETIME], time [#TIME], date [#DATE], gYearMonth [#GYEARMONTH], gMonthDay [#GMONTHDAY], gYear [#GYEAR] gMonth [#GMONTH] and gDay [#GDAY] defined in the XML Namespace "http://www.w3.org/2001/XMLSchema". These datatypes are normatively defined in W3C XML Schema 1.0 Part 2, Section 3.2.7-14 [http://www.w3.org/TR/xmlschema-2/#dateTime]. The table below defines the mapping between XML Schema 1.0 date/time datatype fields and this class' fields. It also summarizes the value constraints for the date and time fields defined in W3C XML Schema 1.0 Part 2, Appendix D, ISO 8601 Date and Time Formats [http://www.w3.org/TR/xmlschema-2/#isoformats]. Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation XML Schema 1.0 datatype RelatedXMLGregorianCalen  Value Range field darAccessor(s) year

javax.xml.datatype.XML  GregorianCalendar.getYear [Method getYear()] + javax.xml.datatype.XML  GregorianCalendar.getEon [Method getEon()] or  javax.xml.datatype.XML  GregorianCalen  dar.getEonAndYear [Method getEonAndYear()]

227

getYear() is a value between -(10^9-1) to (10^9)1 or javax.xml.datatype.Data  typeConstants.FIELD_UN  DEFINED [Field F I E L D _ U N   DEFINED].javax.xml.data  type.XMLGregorianCalen  dar.getEon [Method getEon()] is high order year value in billion of years.getEon() has values greater than or equal to (10^9) or less than or equal

Final 1.0.0

Package javax.xml.datatype

Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation to -(10^9). A value of null indicates field is undefined. Given that XML Schema 1.0 e r r a t a [htp:/www.w3.org/2001/05/xmlschema-errata#e2-63] states that the year zero will be a valid lexical value in a future version of XML Schema, this class allows the year field to be set to zero. Otherwise, the year field value is handled exactly as described in the errata and [ISO-8601-1988]. Note that W3C XML Schema 1.0 val  idation does not allow for the year field to have a value of zero. month

javax.xml.datatype.XML  1 to 12 or javax.xml.data  GregorianCalendar.getMonth t y p e . D a t a t y p e C o n   [Method getMonth()] stants.FIELD_UNDEFINED [Field FIELD_UN  DEFINED]

day

javax.xml.datatype.XML  Independent of month, max GregorianCalendar.getDay range is 1 to 31 or [Method getDay()] javax.xml.datatype.Data  typeConstants.FIELD_UN  DEFINED [Field FIELD_UNDEFINED]. The normative value constraint stated relative to month field's value is in W3C XML Schema 1.0 Part 2, Appendix D [htp:/www.w3.org/TR/xmlschema-2/#isoformats].

hour

javax.xml.datatype.XML  0 to 24 or javax.xml.data  GregorianCalendar.getHour t y p e . D a t a t y p e C o n   [Method getHour()] stants.FIELD_UNDEFINED [Field FIELD_UN  DEFINED]. For a value of 24, the minute and second field must be zero per XML Schema Errata [htp:/www.w3.org/2001/05/xmlschema-errata#e2-45].

minute

javax.xml.datatype.XML  GregorianCalendar.get  Minute [Method get  Minute()]

228

0 to 59 or javax.xml.data  type.DatatypeCon  stants.FIELD_UNDEFINED [Field FIELD_UN  DEFINED]

Final 1.0.0

Package javax.xml.datatype

Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation second

javax.xml.datatype.XML  GregorianCalendar.get  Second [Method get  Second()] + javax.xml.data  type.XMLGregorianCalen  dar.getMillisecond [Method getMillisecond()]/1000 or  javax.xml.datatype.XML  GregorianCalendar.get  Second [Method get  Second()] + javax.xml.data  type.XMLGregorianCalen  dar.getFractionalSecond [Method getFraction  alSecond()]

javax.xml.datatype.XML  GregorianCalendar.get  Second [Method get  Second()] from 0 to 60 or javax.xml.datatype.Data  typeConstants.FIELD_UN  DEFINED [Field F I E L D _ U N   DEFINED].(Note: 60 only allowable for leap second.)javax.xml.data  type.XMLGregorianCalen  dar.getFractionalSecond [Method getFraction  alSecond()] allows for infin  ite precision over the range from 0.0 to 1.0 when the javax.xml.datatype.XML  GregorianCalendar.get  Second [Method get  Second()] is defined.Frac  tionalSecond is optional and has a value of null when it is un  defined.javax.xml.data  type.XMLGregorianCalen  dar.getMillisecond [Method getMillisecond()] is the con  venience millisecond preci  sion of value of javax.xml.datatype.XML  GregorianCalendar.getFrac  tionalSecond [Method get  FractionalSecond()].

timezone

javax.xml.datatype.XML  GregorianCalendar.get  Timezone [Method get  Timezone()]

Number of minutes or javax.xml.datatype.Data  typeConstants.FIELD_UN  DEFINED [Field FIELD_UNDEFINED]. Value range from -14 hours (-14 * 60 minutes) to 14 hours (14 * 60 minutes).

All maximum value space constraints listed for the fields in the table above are checked by factory methods, @{link DatatypeFactory}, setter methods and parse methods of this class. IllegalArgumentException is thrown when a parameter's value is outside the value constraint for the field or if the composite values constitute an invalid XML  GregorianCalendar instance (for example, if the 31st of June is specified). The following operations are defined for this class: •

accessors/mutators for independent date/time fields

229

Final 1.0.0

Package javax.xml.datatype



conversion between this class and W3C XML Schema 1.0 lexical representation, javax.xml.datatype.XMLGregori  anCalendar.toString [ Method toString()], javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar [ Method newXMLGregorianCalendar(java.lang.String)]



conversion between this class and java.util.GregorianCalendar, javax.xml.datatype.XMLGregorianCalendar.to  GregorianCalendar [ Method toGregorianCalendar(java.util.TimeZone, java.util.Locale, javax.xml.datatype.XML  GregorianCalendar)], javax.xml.datatype.DatatypeFactory [ Class DatatypeFactory]



partial order relation comparator method, javax.xml.datatype.XMLGregorianCalendar.compare [ Method com  pare(javax.xml.datatype.XMLGregorianCalendar)]



javax.xml.datatype.XMLGregorianCalendar.equals [ Method equals(java.lang.Object)] defined relative to javax.xml.datatype.XMLGregorianCalendar.compare [ Method compare(javax.xml.datatype.XMLGregorianCal  endar)].



addition operation with javax.xml.datatype.Duration [ Class Duration] instance as defined in W3C XML Schema 1.0 Part 2, Appendix E, Adding durations to d a t e Ti m e s [http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes].

Synopsis public XMLGregorianCalendarimplements Cloneable { public XMLGregorianCalendar(); public void abstract clear(); public void abstract reset(); public void abstract setYear(java.math.BigInteger year); public void abstract setYear(int year); public void abstract setMonth(int month); public void abstract setDay(int day); public void abstract setTimezone(int offset); public void setTime(int hour,                       int minute,                       int second); public void abstract setHour(int hour); public void abstract setMinute(int minute); public void abstract setSecond(int second); public void abstract setMillisecond(int millisecond); public void abstract setFractionalSecond(java.math.BigDecimal fractional); public void setTime(int hour,                       int minute,

230

Final 1.0.0

Package javax.xml.datatype

                      int second,                       java.math.BigDecimal fractional); public void setTime(int hour,                       int minute,                       int second,                       int millisecond); public BigInteger abstract getEon(); public int abstract getYear(); public BigInteger abstract getEonAndYear(); public int abstract getMonth(); public int abstract getDay(); public int abstract getTimezone(); public int abstract getHour(); public int abstract getMinute(); public int abstract getSecond(); public int getMillisecond(); public BigDecimal abstract getFractionalSecond(); public int abstract compare(javax.xml.datatype.XMLGregorianCalendar xmlGregorianCalendar); public XMLGregorianCalendar abstract normalize(); public boolean equals(java.lang.Object obj); public int hashCode(); public String abstract toXMLFormat(); public QName abstract getXMLSchemaType(); public String toString(); public boolean abstract isValid(); public void abstract add(javax.xml.datatype.Duration duration); public GregorianCalendar abstract toGregorianCalendar();

public GregorianCalendar abstract toGregorianCalendar(java.util.TimeZone timezone,                                                         java.util.Locale aLocale,                                                         javax.xml.datatype.XMLGregorianCale public TimeZone abstract getTimeZone(int defaultZoneoffset); public Object abstract clone();

231

Final 1.0.0

Package javax.xml.datatype

} Author

Joseph Fialli [mailto:[email protected]], Kohsuke Kawaguchi [mailto:[email protected]], Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.28.4.2.2.4.2.1.2.2.2.6 $, $Date: 2004/06/09 19:06:01 $

Since

1.5

See Also

javax.xml.datatype.Duration [Class Duration], javax.xml.datatype.DatatypeFactory [Class Data  typeFactory]

Inheritance Path java.lang.Object | javax.xml.datatype.XMLGregorianCalendar

Members Method add(Duration) public void abstract add(javax.xml.datatype.Duration duration);

Parameters duration

Duration to add to this XMLGregorianCalendar227.

Exceptions NullPointerException

when duration parameter is null.

Add duration to this instance. The computation is specified in XML Schema 1.0 Part 2, Appendix E, Adding durations to dateTimes> [http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes]. date/time field mapping table [#datetimefieldsmapping] defines the mapping from XML Schema 1.0 dateTime fields to this class' representation of those fields.

Method clear() public void abstract clear(); Unset all fields to undefined. Set all int fields to javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] and reference fields to null.

Method clone() public Object abstract clone(); Creates and returns a copy of this object.

232

Final 1.0.0

Package javax.xml.datatype

Method compare(XMLGregorianCalendar) public int abstract compare(javax.xml.datatype.XMLGregorianCalendar xmlGregorianCalendar);

Parameters xmlGregorianCalendar

Instance of XMLGregorianCalendar227 to compare

returns

The relationship between this XMLGregorianCalendar227 and the specified xml  GregorianCalendar as javax.xml.datatype.DatatypeConstants.LESSER [ Field LESSER], javax.xml.datatype.DatatypeConstants.EQUAL [ Field EQUAL], javax.xml.datatype.DatatypeConstants.GREATER [ Field GREATER] or javax.xml.datatype.DatatypeConstants.INDETERMINATE [ Field INDETERMINATE].

Exceptions NullPointerException

if xmlGregorianCalendar is null.

Compare two instances of W3C XML Schema 1.0 date/time datatypes according to partial order relation defined in W3C XML Schema 1.0 Part 2, Section 3.2.7.3, Order relation on dateTime [http://www.w3.org/TR/xmlschema-2/#dateTime-order]. xsd:dateTime datatype field mapping to accessors of this class are defined in date/time field mapping table [#datetimefieldmapping].

Method equals(Object) public boolean equals(java.lang.Object obj);

Parameters obj

to compare.

returns

true when obj is an instance of XMLGregorianCalendar227 and javax.xml.datatype.XML  GregorianCalendar.compare [ Method compare(javax.xml.datatype.XMLGregorianCalendar)] returns javax.xml.datatype.DatatypeConstants.EQUAL [ Field EQUAL], otherwise false.

Exceptions NullPointerException

If obj is null.

Indicates whether parameter obj is "equal to" this one.

Method getDay() public int abstract getDay(); See Also

javax.xml.datatype.XMLGregorianCalendar.setDay [Method setDay(int)]

Return day in month or javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. Value constraints for this value are summarized in day field of date/time field mapping table [#datetimefield-day].

233

Final 1.0.0

Package javax.xml.datatype

Method getEon() public BigInteger abstract getEon(); See Also

javax.xml.datatype.XMLGregorianCalendar.getYear [Method getYear()], javax.xml.datatype.XM  LGregorianCalendar.getEonAndYear [Method getEonAndYear()]

Return high order component for XML Schema 1.0 dateTime datatype field for year. null if this optional part of the year field is not defined. Value constraints for this value are summarized in year field of date/time field mapping table [#datetimefield-year].

Method getEonAndYear() public BigInteger abstract getEonAndYear(); See Also

javax.xml.datatype.XMLGregorianCalendar.getEon [Method getEon()], javax.xml.datatype.XM  LGregorianCalendar.getYear [Method getYear()]

Return XML Schema 1.0 dateTime datatype field for year. Value constraints for this value are summarized in year field of date/time field mapping table [#datetimefield-year].

Method getFractionalSecond() public BigDecimal abstract getFractionalSecond(); See Also

javax.xml.datatype.XMLGregorianCalendar.getSecond [Method getSecond()], javax.xml.data  type.XMLGregorianCalendar.setTime [Method setTime(int, int, int, java.math.BigDecimal)]

Return fractional seconds. null is returned when this optional field is not defined. Value constraints are detailed in second field of date/time field mapping table [#datetimefield-second]. This optional field can only have a defined value when the xs:dateTime second field, represented by javax.xml.data  type.XMLGregorianCalendar.getSecond [ Method getSecond()], does not return javax.xml.datatype.DatatypeCon  stants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED].

Method getHour() public int abstract getHour(); See Also

javax.xml.datatype.XMLGregorianCalendar.setTime [Method setTime(int, int, int)]

Return hours or javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. Returns javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] if this field is not defined. Value constraints for this value are summarized in hour field of date/time field mapping table [#datetimefield-hour].

Method getMillisecond() public int getMillisecond();

234

Final 1.0.0

Package javax.xml.datatype

See Also

javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [Method getFractionalSecond()], javax.xml.datatype.XMLGregorianCalendar.setTime [Method setTime(int, int, int)]

Return millisecond precision of javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFrac  tionalSecond()]. This method represents a convenience accessor to infinite precision fractional second value returned by javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFractionalSecond()]. The returned value is the rounded down to milliseconds value of javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFractionalSecond()]. When javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFractionalSecond()] returns null, this method must return javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED]. Value constraints for this value are summarized in second field of date/time field mapping table [#datetimefield-second].

Method getMinute() public int abstract getMinute(); See Also

javax.xml.datatype.XMLGregorianCalendar.setTime [Method setTime(int, int, int)]

Return minutes or javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. Returns javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] if this field is not defined. Value constraints for this value are summarized in minute field of date/time field mapping table [#datetimefield-minute].

Method getMonth() public int abstract getMonth(); Return number of month or javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. Value constraints for this value are summarized in month field of date/time field mapping table [#datetimefield-month].

Method getSecond() public int abstract getSecond(); See Also

javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [Method getFractionalSecond()], javax.xml.datatype.XMLGregorianCalendar.getMillisecond [Method getMillisecond()], javax.xml.datatype.XMLGregorianCalendar.setTime [Method setTime(int, int, int)]

Return seconds or javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. Returns javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] if this field is not defined. When this field is not defined, the optional xs:dateTime fractional seconds field, represented by javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFractionalSecond()] and javax.xml.datatype.XMLGregorianCalendar.getMillisecond [ Method getMillisecond()], must not be defined. Value constraints for this value are summarized in second field of date/time field mapping table [#datetimefield-second].

235

Final 1.0.0

Package javax.xml.datatype

Method getTimezone() public int abstract getTimezone(); See Also

javax.xml.datatype.XMLGregorianCalendar.setTimezone [Method setTimezone(int)]

Return timezone offset in minutes or javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] if this optional field is not defined. Value constraints for this value are summarized in timezone field of date/time field mapping table [#datetimefield-timezone].

Method getTimeZone(int) public TimeZone abstract getTimeZone(int defaultZoneoffset);

Parameters defaultZoneoffset

default zoneoffset if this zoneoffset is javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

returns

TimeZone for this.

Returns a java.util.TimeZone for this class. If timezone field is defined for this instance, returns TimeZone initialized with custom timezone id of zoneoffset. If timezone field is undefined, try the defaultZoneoffset that was passed in. If defaultZoneoffset is FIELD_UNDEFINED, return default timezone for this host. (Same default as java.util.GregorianCalendar).

Method getXMLSchemaType() public QName abstract getXMLSchemaType();

Exceptions java.lang.IllegalStateEx  ception

if the combination of set fields does not match one of the eight defined XML Schema builtin date/time datatypes.

Return the name of the XML Schema date/time type that this instance maps to. Type is computed based on fields that are set. Required fields for XML Schema 1.0 Date/Time Datatypes.(timezone is optional for all date/time datatypes) Datatype

year

month

day

hour

minute

second

javax.xml.data  X type.Data  typeCon  stants.DATE  TIME [Field DATETIME]

X

X

X

X

X

javax.xml.data  X type.Data  typeCon 

X

X

236

Final 1.0.0

Package javax.xml.datatype

Required fields for XML Schema 1.0 Date/Time Datatypes.(timezone is optional for all date/time datatypes) s t a n t s . DAT E [Field DATE] javax.xml.data  type.Data  typeCon  stants.TIME [Field TIME]

X

javax.xml.data  X type.Data  typeCon  stants.GYEAR  MONTH [Field G Y E A R   MONTH]

X

javax.xml.data  type.Data  typeCon  stants.GMONTHDAY [ F i e l d GMONTHDAY]

X

X

X

X

javax.xml.data  X type.Data  typeCon  stants.GYEAR [Field GYEAR] javax.xml.data  type.Data  typeCon  stants.GMONTH [ F i e l d GMONTH]

X

javax.xml.data  type.Data  typeCon  stants.GDAY [Field GDAY]

X

Method getYear() public int abstract getYear(); See Also

javax.xml.datatype.XMLGregorianCalendar.getEon [Method getEon()], javax.xml.datatype.XM  LGregorianCalendar.getEonAndYear [Method getEonAndYear()]

Return low order component for XML Schema 1.0 dateTime datatype field for year or javax.xml.datatype.Data  typeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED]. Value constraints for this value are summarized in year field of date/time field mapping table [#datetimefield-year].

237

Final 1.0.0

Package javax.xml.datatype

Method hashCode() public int hashCode(); Returns a hash code consistent with the definition of the equals method.

Method isValid() public boolean abstract isValid(); Validate instance by getXMLSchemaType() constraints.

Method normalize() public XMLGregorianCalendar abstract normalize(); Normalize this instance to UTC. 2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z Implements W3C XML Schema Part 2, Section 3.2.7.3 (A).

Method reset() public void abstract reset(); Reset this XMLGregorianCalendar227 to its original values. XMLGregorianCalendar227 is reset to the same values as when it was created with javax.xml.datatype.DatatypeFact  ory.newXMLGregorianCalendar [ Method newXMLGregorianCalendar()], javax.xml.datatype.DatatypeFactory.newXM  LGregorianCalendar [ Method newXMLGregorianCalendar(java.lang.String)], javax.xml.datatype.DatatypeFact  ory.newXMLGregorianCalendar [ Method newXMLGregorianCalendar(java.math.BigInteger, int, int, int, int, int, java.math.BigDecimal, int)], javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar [ Method newXML  GregorianCalendar(int, int, int, int, int, int, int, int)], javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendar [ Method newXMLGregorianCalendar(java.util.GregorianCalendar)], javax.xml.datatype.DatatypeFactory.newXML  GregorianCalendarDate [ Method newXMLGregorianCalendarDate(int, int, int, int)], javax.xml.datatype.DatatypeFact  ory.newXMLGregorianCalendarTime [ Method newXMLGregorianCalendarTime(int, int, int, int)], javax.xml.data  type.DatatypeFactory.newXMLGregorianCalendarTime [ Method newXMLGregorianCalendarTime(int, int, int, java.math.BigDecimal, int)] or javax.xml.datatype.DatatypeFactory.newXMLGregorianCalendarTime [ Method newXMLGregorianCalendarTime(int, int, int, int, int)]. reset() is designed to allow the reuse of existing XMLGregorianCalendar227s thus saving resources associated with the creation of new XMLGregorianCalendar227s.

Method setDay(int) public void abstract setDay(int day);

Parameters day

value constraints summarized in day field of date/time field mapping table [#datetimefield-day].

238

Final 1.0.0

Package javax.xml.datatype

Exceptions IllegalArgumentException

if day parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set days in month. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

Method setFractionalSecond(BigDecimal) public void abstract setFractionalSecond(java.math.BigDecimal fractional);

Parameters fractional

value constraints summarized in fractional field of date/time field mapping table [#datetimefield-fractional].

Exceptions IllegalArgumentException

if fractional parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set fractional seconds. Unset this field by invoking the setter with a parameter value of null.

Method setHour(int) public void abstract setHour(int hour);

Parameters hour

value constraints summarized in hour field of date/time field mapping table [#datetimefield-hour].

Exceptions IllegalArgumentException

if hour parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set hours. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

Method setMillisecond(int) public void abstract setMillisecond(int millisecond);

Parameters millisecond

value constraints summarized in millisecond field of date/time field mapping table [#datetimefield-millisecond].

239

Final 1.0.0

Package javax.xml.datatype

Exceptions IllegalArgumentException

if millisecond parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set milliseconds. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

Method setMinute(int) public void abstract setMinute(int minute);

Parameters minute

value constraints summarized in minute field of date/time field mapping table [#datetimefield-minute].

Exceptions IllegalArgumentException

if minute parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set minutes. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

Method setMonth(int) public void abstract setMonth(int month);

Parameters month

value constraints summarized in month field of date/time field mapping table [#datetimefield-month].

Exceptions IllegalArgumentException

if month parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set month. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

Method setSecond(int) public void abstract setSecond(int second);

Parameters second

value constraints summarized in second field of date/time field mapping table [#datetimefield-second].

240

Final 1.0.0

Package javax.xml.datatype

Exceptions IllegalArgumentException

if second parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set seconds. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

Method setTime(int, int, int) public void setTime(int hour,                       int minute,                       int second);

Parameters hour

value constraints are summarized in hour field of date/time field mapping table [#datetimefield-hour].

minute

value constraints are summarized in minute field of date/time field mapping table [#datetimefield-minute].

second

value constraints are summarized in second field of date/time field mapping table [#datetimefield-second].

Exceptions IllegalArgumentException See Also

if any parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

javax.xml.datatype.XMLGregorianCalendar.setTime java.math.BigDecimal)]

[Method

setTime(int,

int,

int,

Set time as one unit.

Method setTime(int, int, int, BigDecimal) public void setTime(int hour,                       int minute,                       int second,                       java.math.BigDecimal fractional);

Parameters hour

value constraints are summarized in hour field of date/time field mapping table [#datetimefield-hour].

minute

value constraints are summarized in minute field of date/time field mapping table [#datetimefield-minute].

second

value constraints are summarized in second field of date/time field mapping table [#datetimefield-second].

fractional

value of null indicates this optional field is not set.

241

Final 1.0.0

Package javax.xml.datatype

Exceptions IllegalArgumentException

if any parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set time as one unit, including the optional infinite precision fractional seconds.

Method setTime(int, int, int, int) public void setTime(int hour,                       int minute,                       int second,                       int millisecond);

Parameters hour

value constraints are summarized in hour field of date/time field mapping table [#datetimefield-hour].

minute

value constraints are summarized in minute field of date/time field mapping table [#datetimefield-minute].

second

value constraints are summarized in second field of date/time field mapping table [#datetimefield-second].

millisecond

value of javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED FIELD_UNDEFINED] indicates this optional field is not set.

[

Field

Exceptions IllegalArgumentException

if any parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set time as one unit, including optional milliseconds.

Method setTimezone(int) public void abstract setTimezone(int offset);

Parameters offset

value constraints summarized [#datetimefield-timezone].

in

timezone

field

of

date/time

field

mapping

table

Exceptions IllegalArgumentException

if offset parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set the number of minutes in the timezone offset. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED].

242

Final 1.0.0

Package javax.xml.datatype

Method setYear(BigInteger) public void abstract setYear(java.math.BigInteger year);

Parameters year

value constraints summarized in year field of date/time field mapping table [#datetimefield-year].

Exceptions IllegalArgumentException

if year parameter is outside value constraints for the field as specified in date/time field mapping table [#datetimefieldmapping].

Set low and high order component of XSD dateTime year field. Unset this field by invoking the setter with a parameter value of null.

Method setYear(int) public void abstract setYear(int year);

Parameters year

value constraints are summarized in year field of date/time field mapping table [#datetimefield-year]. If year is javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED], then eon is set to null.

Set year of XSD dateTime year field. Unset this field by invoking the setter with a parameter value of javax.xml.datatype.DatatypeConstants.FIELD_UN  DEFINED [ Field FIELD_UNDEFINED]. Note: if the absolute value of the year parameter is less than 10^9, the eon component of the XSD year field is set to null by this method.

Method toGregorianCalendar() public GregorianCalendar abstract toGregorianCalendar(); See Also

javax.xml.datatype.XMLGregorianCalendar.toGregorianCalendar [Method toGregorianCalen  dar(java.util.TimeZone, java.util.Locale, javax.xml.datatype.XMLGregorianCalendar)]

Convert this XMLGregorianCalendar227 to a java.util.GregorianCalendar. When this instance has an undefined field, this conversion relies on the java.util.GregorianCalendar default for its corresponding field. A notable difference between XML Schema 1.0 date/time datatypes and java.util.GregorianCalendar is that Timezone value is optional for date/time datatypes and it is a required field for java.util.GregorianCalendar. See javadoc for java.util.TimeZone.getDefault() on how the default is determined. To explicitly specify the TimeZone instance, see javax.xml.datatype.XMLGregorian  Calendar.toGregorianCalendar [ Method toGregorianCalendar(java.util.TimeZone, java.util.Locale, javax.xml.data  type.XMLGregorianCalendar)].

243

Final 1.0.0

Package javax.xml.datatype

Field by Field Conversion from this class to java.util.GregorianCalendar java.util.GregorianCalendar field

javax.xml.datatype.XMLGregorianCalendar field

ERA

javax.xml.datatype.XMLGregorianCalendar.getEonAn  dYear [Method getEonAndYear()].signum() < 0 ? GregorianCalendar.BC : GregorianCalen  dar.AD

YEAR

javax.xml.datatype.XMLGregorianCalendar.getEonAn  dYear [Method getEonAndYear()].abs().int  Value()*

MONTH

javax.xml.datatype.XMLGregorianCalendar.getMonth [Method getMonth()] - javax.xml.datatype.DatatypeCon  stants.JANUARY [Field JANUARY] + java.util.Calen  dar.JANUARY

DAY_OF_MONTH

javax.xml.datatype.XMLGregorianCalendar.getDay [Method getDay()]

HOUR_OF_DAY

javax.xml.datatype.XMLGregorianCalendar.getHour [Method getHour()]

MINUTE

javax.xml.datatype.XMLGregorianCalendar.getMinute [Method getMinute()]

SECOND

javax.xml.datatype.XMLGregorianCalendar.getSecond [Method getSecond()]

MILLISECOND

get millisecond order from javax.xml.datatype.XML  GregorianCalendar.getFractionalSecond [Method getFrac  tionalSecond()]*

GregorianCalendar.setTimeZone(TimeZone) javax.xml.datatype.XMLGregorianCalendar.getTimezone [Method getTimezone()] formatted into Custom timezone id * designates possible loss of precision during the conversion due to source datatype having higher precision than target datatype. To ensure consistency in conversion implementations, the new GregorianCalendar should be instantiated in following manner. •

Using timeZone value as defined above, create a new java.util.GregorianCalendar(timeZone,Loc  ale.getDefault()).



Initialize all GregorianCalendar fields by calling {(@link GegorianCalendar#clear()}.



Obtain a pure Gregorian Calendar by invoking GregorianCalendar.setGregorianChange( new Date(Long.MIN_VALUE)).



Its fields ERA, YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, SECOND and MILLISECOND are set using the method Calendar.set(int,int)

Method toGregorianCalendar(TimeZone, Locale, XMLGregorianCalendar)

public GregorianCalendar abstract toGregorianCalendar(java.util.TimeZone timezone,                                                         java.util.Locale aLocale,                                                         javax.xml.datatype.XMLGregorianCale

244

Final 1.0.0

Package javax.xml.datatype

Parameters timezone

provide Timezone. null is a legal value.

aLocale

provide explicit Locale. Use default GregorianCalendar locale if value is null.

defaults

provide default field values to use when corresponding field for this instance is FIELD_UN  DEFINED or null. If defaultsis null or a field within the specified defaults is undefined, just use java.util.GregorianCalendar defaults.

returns

a java.util.GregorianCalendar conversion of this instance.

Convert this XMLGregorianCalendar227 along with provided parameters to a java.util.GregorianCalendar instance. Since XML Schema 1.0 date/time datetypes has no concept of timezone ids or daylight savings timezone ids, this conversion operation allows the user to explicitly specify one with timezone parameter. To compute the return value's TimeZone field, •

when parameter timeZone is non-null, it is the timezone field.



else when this.getTimezone() != FIELD_UNDEFINED, create a java.util.TimeZone with a custom timezone id using the this.getTimezone().



else when defaults.getTimezone() != FIELD_UNDEFINED, create a java.util.TimeZone with a custom timezone id using defaults.getTimezone().



else use the GregorianCalendar default timezone value for the host is defined as specified by java.util.TimeZone.getDefault().

• •

Method toString() public String toString();

Exceptions IllegalStateException See Also

if the combination of set fields does not match one of the eight defined XML Schema builtin date/time datatypes.

javax.xml.datatype.XMLGregorianCalendar.toXMLFormat [Method toXMLFormat()]

Returns a String representation of this XMLGregorianCalendar227 Object. The result is a lexical representation generated by javax.xml.datatype.XMLGregorianCalendar.toXMLFormat [ Method toXMLFormat()].

Method toXMLFormat() public String abstract toXMLFormat();

245

Final 1.0.0

Package javax.xml.datatype

Exceptions IllegalStateException

if the combination of set fields does not match one of the eight defined XML Schema builtin date/time datatypes.

Return the lexical representation of this instance. The format is specified in XML Schema 1.0 Part 2, Section 3.2.[714].1, Lexical Representation". [http://www.w3.org/TR/xmlschema-2/#dateTime-order] Specific target lexical representation format is determined by javax.xml.datatype.XMLGregorianCalendar.getXMLS  chemaType [ Method getXMLSchemaType()].

Exception DatatypeConfigurationException Indicates a serious configuration error. TODO: support all constructors

Synopsis public DatatypeConfigurationException extends Exception { public DatatypeConfigurationException(); public DatatypeConfigurationException(java.lang.String message); public DatatypeConfigurationException(java.lang.String message,                                         java.lang.Throwable cause); public DatatypeConfigurationException(java.lang.Throwable cause); } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.1 $, $Date: 2004/03/06 00:22:23 $

Since

1.5

Inheritance Path java.lang.Object | java.lang.Throwable | java.lang.Exception | javax.xml.datatype.DatatypeConfigurationException

246

Final 1.0.0

Package javax.xml.datatype

Members Constructor DatatypeConfigurationException() public DatatypeConfigurationException(); Create a new DatatypeConfigurationException with no specified detail mesage and cause.

Constructor DatatypeConfigurationException(String) public DatatypeConfigurationException(java.lang.String message);

Parameters message

The detail message.

Create a new DatatypeConfigurationException with the specified detail message.

Constructor DatatypeConfigurationException(String, Throwable) public DatatypeConfigurationException(java.lang.String message,                                         java.lang.Throwable cause);

Parameters message

The detail message.

cause

The cause. A null value is permitted, and indicates that the cause is nonexistent or unknown.

Create a new DatatypeConfigurationException with the specified detail message and cause.

Constructor DatatypeConfigurationException(Throwable) public DatatypeConfigurationException(java.lang.Throwable cause);

Parameters cause

The cause. A null value is permitted, and indicates that the cause is nonexistent or unknown.

Create a new DatatypeConfigurationException with the specified cause.

247

Final 1.0.0

Chapter 16. Package javax.xml Defines core XML constants and functionality from the XML specifications. The following core XML standards apply: •

Extensible Markup Language (XML) 1.1 [http://www.w3.org/TR/xml11/]



Extensible Markup Language (XML) 1.0 (Second Edition) [http://www.w3.org/TR/REC-xml]



XML 1.0 Second Edition Specification Errata [http://www.w3.org/XML/xml-V10-2e-errata]



Namespaces in XML 1.1 [http://www.w3.org/TR/xml-names11/]



Namespaces in XML [http://www.w3.org/TR/REC-xml-names/#ns-qualnames]



Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata]

Class XMLConstants Utility class to contain basic XML values as constants.

Synopsis final XMLConstants { } Author

Jeff Suttor [mailto:[email protected]]

Version

$Revision: 1.10.12.1 $, $Date: 2004/05/05 20:04:51 $

Since

1.5

See Also

Extensible Markup Language (XML) 1.1 [http://www.w3.org/TR/xml11/], Extensible Markup Language (XML) 1.0 (Second Edition) [http://www.w3.org/TR/REC-xml], XML 1.0 Second Edition Specification Errata [http://www.w3.org/XML/xml-V10-2e-errata], Namespaces in XML 1.1 [http://www.w3.org/TR/xml-names11/], Namespaces in XML [http://www.w3.org/TR/REC-xml-names], Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata], XML Schema Part 1: Structures [http://www.w3.org/TR/xmlschema-1/]

Inheritance Path java.lang.Object | javax.xml.XMLConstants

Members Field DEFAULT_NS_PREFIX   static java.lang.String DEFAULT_NS_PREFIX ;

248

Final 1.0.0

Package javax.xml

See Also

Namespaces in XML, 3. Qualified Names [http://www.w3.org/TR/REC-xml-names/#ns-qualnames]

Prefix to use to represent the default XML Namespace. Defined by the XML specification to be "".

Field FEATURE_SECURE_PROCESSING   static java.lang.String FEATURE_SECURE_PROCESSING ; Feature for secure processing. •

true instructs the implementation to process XML securely. This may set limits on XML constructs to avoid conditions such as denial of service attacks.



false instructs the implementation to process XML acording the letter of the XML specifications ingoring security issues such as limits on XML constructs to avoid conditions such as denial of service attacks.

Field NULL_NS_URI   static java.lang.String NULL_NS_URI ; See Also

Namespaces in XML, 5.2 [http://www.w3.org/TR/REC-xml-names/#defaulting]

Namespace

Defaulting

Namespace URI to use to represent that there is no Namespace. Defined by the Namespace specification to be "".

Field RELAXNG_NS_URI   static java.lang.String RELAXNG_NS_URI ; See Also

RELAX NG Specification [http://relaxng.org/spec-20011203.html]

RELAX NG Namespace URI. Defined to be " http://relaxng.org/ns/structure/1.0".

Field W3C_XML_SCHEMA_INSTANCE_NS_URI   static java.lang.String W3C_XML_SCHEMA_INSTANCE_NS_URI ; See Also

XML Schema Part 1: Structures, 2.6 Schema-Related Markup in Documents Being Validated [http://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions]

W3C XML Schema Instance Namespace URI. Defined to be " http://www.w3.org/2001/XMLSchema-instance".

Field W3C_XML_SCHEMA_NS_URI   static java.lang.String W3C_XML_SCHEMA_NS_URI ;

249

Final 1.0.0

Package javax.xml

See Also

XML Schema Part 1: Structures, 2.6 Schema-Related Markup in Documents Being Validated [http://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions]

W3C XML Schema Namespace URI. Defined to be " http://www.w3.org/2001/XMLSchema".

Field W3C_XPATH_DATATYPE_NS_URI   static java.lang.String W3C_XPATH_DATATYPE_NS_URI ; See Also

XQuery 1.0 and XPath 2.0 Data Model [http://www.w3.org/TR/xpath-datamodel]

W3C XPath Datatype Namespace URI. Defined to be " http://www.w3.org/2003/11/xpath-datatypes".

Field XML_DTD_NS_URI   static java.lang.String XML_DTD_NS_URI ; XML Document Type Declaration Namespace URI as an arbitrary value. Since not formally defined by any existing standard, arbitrarily define to be " http://www.w3.org/TR/RECxml".

Field XML_NS_PREFIX   static java.lang.String XML_NS_PREFIX ; See Also

Namespaces in XML, 3. Qualified Names< [http://www.w3.org/TR/REC-xml-names/#ns-qualnames]

The official XML Namespace prefix. Defined by the XML specification to be " xml".

Field XML_NS_URI   static java.lang.String XML_NS_URI ; See Also

Namespaces in XML, 3. Qualified Names [http://www.w3.org/TR/REC-xml-names/#ns-qualnames]

The official XML Namespace name URI. Defined by the XML specification to be " http://www.w3.org/XML/1998/namespace".

Field XMLNS_ATTRIBUTE   static java.lang.String XMLNS_ATTRIBUTE ; See Also

Namespaces in XML, 3. Qualified Names [http://www.w3.org/TR/REC-xml-names/#ns-qualnames]

The official XML attribute used for specifying XML Namespace declarations. It is NOT valid to use as a prefix. Defined by the XML specification to be " xmlns".

250

Final 1.0.0

Package javax.xml

Field XMLNS_ATTRIBUTE_NS_URI   static java.lang.String XMLNS_ATTRIBUTE_NS_URI ; See Also

Namespaces in XML, 3. Qualified Names [http://www.w3.org/TR/REC-xml-names/#ns-qualnames], Namespaces in XML Errata [http://www.w3.org/XML/xml-names-19990114-errata/]

The official XML attribute used for specifying XML Namespace declarations, XMLConstants.XMLNS_ATTRIBUTE [ Field XMLNS_ATTRIBUTE], Namespace name URI. Defined by the XML specification to be " http://www.w3.org/2000/xmlns/".

251

Final 1.0.0

Chapter 17. Colophon Talk the Talk, Walk the Walk JSR 206 Java™ API for XML Processing (JAXP) 1.3 was authored in XML using the DocBook [http://docbook.org/] DTD. The XML was transformed into XHTML, HTML and XSL Formatting Objects using the DocBook style sheets. The XSL Formatting Objects were then transformed into PDF.

Table 17.1. XML Usage Conventions

"external-spec" is the type of all ulinks that refer to external specifications



"organization" is the type of all ulinks that refer to organ  izations

252

Final 1.0.0

JSR 206 Java API for XML Processing (JAXP) 1.3

and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and ...... Feature names are fully qualified java.net.

1MB Sizes 13 Downloads 151 Views

Recommend Documents

JSR 206 Java API for XML Processing (JAXP) 1.3
Like HTML, XML makes use of tags and attributes. Tags are words ... please send email to . You can ...... Jeff Suttor [mailto:Jeff.

XML Schema - Computer Science E-259: XML with Java
Dec 3, 2007 - ..... An all group is used to indicate that all elements should appear, in any ...

Efficient Query Processing for Streamed XML Fragments
Institute of Computer System, Northeastern University, Shenyang, China ... and queries on parts of XML data require less memory and processing time.

pdf to xml converter java
Page 1. Whoops! There was a problem loading more pages. pdf to xml converter java. pdf to xml converter java. Open. Extract. Open with. Sign In. Main menu.

Java Data Access—JDBC, JNDI, and JAXP
Bachelor of Science degree from James Madison University in 1990, and his Master of Science ...... Companies also build online stores using live inventory levels that sell directly ..... Rows represent entries like patient medical records or customer

xml java tutorial pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. xml java tutorial ...

pdf to xml conversion java
Sign in. Loading… Whoops! There was a problem loading more pages. Retrying... Whoops! There was a problem previewing this document. Retrying.

Java Data Access—JDBC, JNDI, and JAXP
For general information on Hungry Minds' products and services please ...... and retrieve Java objects from a B−tree storage structure stored on a hard drive.

Notio - A Java API for developing CG tools - Semantic Scholar
providing a platform for the development of tools and applications. ... to access the underlying graph implementation (e.g. Deakin Toolset [3] and CGKEE. [4]).

7.2 - Administrative API Developer's Guide: Java
Use the following properties to view data source feed records and content. Note: You can only .... addGsaContent("crawlSchedule", "0,0300,360\n2,0000,1200");.

7.4 - Administrative API Developer's Guide: Java
... Guide: Java. Google Search Appliance software version 7.2 and later ... Authenticating Your Google Search Appliance Account. 7. Content Sources. 8.

adobe pdf java api
... doesn't start automatically. Page 1 of 1. adobe pdf java api. adobe pdf java api. Open. Extract. Open with. Sign In. Main menu. Displaying adobe pdf java api.

java pdf api open source
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. java pdf api open source. java pdf api open source. Open. Extract.

adobe pdf java api
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. adobe pdf java api. adobe pdf java api. Open. Extract. Open with.

Optimizing Differential XML Processing by Leveraging ...
critical business applications. ... Although our approach has promising performance benefits, some limitations were observed in our ..... Technology for. Efficient.

The Space Complexity of Processing XML Twig ... - Research at Google
and Google Haifa Engineering Center. Haifa, Israel. [email protected] ..... which we call basic twig queries. Many existing algo- rithms focus on this type ...

206.pdf
9 SHAHANA.H 21914 - G.H.S KUZHALMANNAM 0 B 3. 10 SULFEENA T S 21408 - G. L. P. S. Peringottukurissi 0 B 3. 11 JAMSIYA.S 21425 - K. J. B. S. Kuthanur 0 C 1. 12 MUHAMMAD RAFI K. P. 21915 - G.H.S. BEMMANUR 0 C 1. Whoops! There was a problem loading this

A Case for XML - IJEECS
butions. For starters, we propose a novel methodology for the investigation of check- sums (TAW), which we use to verify that simulated annealing and operating systems are generally incompatible. We use decen- tralized archetypes to verify that super

A Case for XML - IJEECS
With these considerations in mind, we ran four novel experiments: (1) we measured instant messenger and RAID array throughput on our 2-node testbed; (2) we ...

Computer Science E-259 XML with Java Lecture 2
Sep 24, 2007 - This is an XML document that describes students -->.