jsr 206 java api for xml processing (jaxp) 1 · the jsr 206 java™api for xml processing (jaxp)...

262
JSR 206 Java API for XML Processing (JAXP) 1.3 Jeff Suttor <[email protected]> Norman Walsh <[email protected]> Kohsuke Kawaguchi <[email protected]>

Upload: others

Post on 21-Jul-2020

95 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JSR 206 Java API for XML Processing (JAXP) 1 · 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

JSR 206 Java API for XML Processing(JAXP) 1.3

Jeff Suttor <[email protected]>Norman Walsh <[email protected]>

Kohsuke Kawaguchi <[email protected]>

Page 2: JSR 206 Java API for XML Processing (JAXP) 1 · 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

JSR 206 Java™ API for XML Processing (JAXP) 1.3by Jeff Suttor, Norman Walsh, and Kohsuke KawaguchiCopyright © 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 JavaCommunity that are reviewing this Java Specification Request. All comments, feedback and guidance from the JavaCommunity is appreciated.

Please submit comments to <[email protected]>.

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 tosublicense), under the Sun’s applicable intellectual property rights to view, download, use and reproduce the Specification only for the purpose ofinternal evaluation, which shall be understood to include developing applications intended to run on an implementation of the Specification providedthat 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 anyapplicable copyrights or patent rights it may have in the Specification to create and/or distribute an Independent Implementation of the Specificationthat: (i) fully implements the Spec(s) including all its required interfaces and functionality; (ii) does not modify, subset, superset or otherwise extendthe Licensor Name Space, or include any public or protected packages, classes, Java interfaces, fields or methods within the Licensor Name Spaceother than those required/authorized by the Specification or Specifications being implemented; and (iii) passes the TCK (including satisfying therequirements of the applicable TCK Users Guide) for such Specification. The foregoing license is expressly conditioned on your not acting outsideits 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 grantconcerning 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 otherwisepass through to your licensees any licenses under Sun’s applicable intellectual property rights; nor (b) authorize your licensees to make any claimsconcerning 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 anyof 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 orbinary 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 successorsor 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 scopeof 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 SpecificationLead’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 NON-INFRINGEMENT, THAT THE CONTENTS OF THE SPECIFICATION ARE SUITABLE FOR ANY PURPOSE OR THAT ANY PRACTICE

Final 1.0.0

Page 3: JSR 206 Java API for XML Processing (JAXP) 1 · 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

OR IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETSOR 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 PERIODICALLYADDED 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) DESCRIBEDIN 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 ORRELATED TO ANY FURNISHING, PRACTICING, MODIFYING OR ANY USE OF THE SPECIFICATION, EVEN IF SUN AND/OR ITSLICENSORS 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 ofany 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 orsubcontractor (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 and12.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-confidentialbasis, and (ii) grant Sun a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable license, with the right to sublicense through multiple levelsof 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 InternationalSale 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 tocomply strictly with all such laws and regulations and acknowledges that it has the responsibility to obtain such licenses to export, re-export or importas 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 otherparty, 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 willbe binding, unless in writing and signed by an authorized representative of each party.

(Sun.CfcsSpec.license.11.14.2003)

Final 1.0.0

Page 4: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Table of Contents1. Overview ........................................................................................................................................ 1

What is XML? ............................................................................................................................ 1XML and the Java Platform ........................................................................................................... 1About This Specification ............................................................................................................... 1Who Should Read This Document .................................................................................................. 2Report and Contact ...................................................................................................................... 2Development of This Specification .................................................................................................. 2Acknowledgments ....................................................................................................................... 3

2. Endorsed Specifications ..................................................................................................................... 4Extensible Markup Language (XML) .............................................................................................. 4Namespaces in XML .................................................................................................................... 4XML Schema ............................................................................................................................. 4XSL Transformations (XSLT) ........................................................................................................ 5XML Path Language (XPath) ......................................................................................................... 5XML Inclusions (XInclude) ........................................................................................................... 5Document Object Model (DOM) Level 3 ......................................................................................... 5Simple API for XML (SAX) .......................................................................................................... 6

3. Plugability Layer .............................................................................................................................. 7SAX Plugability .......................................................................................................................... 7

Examples ........................................................................................................................... 7DOM Plugability ......................................................................................................................... 8

Reliance on SAX API ........................................................................................................... 9Examples ........................................................................................................................... 9

XSLT Plugability ....................................................................................................................... 10Examples ......................................................................................................................... 10

XPath Plugability ....................................................................................................................... 15Examples ......................................................................................................................... 16

Validation Plugability ................................................................................................................. 16Thread Safety ............................................................................................................................ 17Properties For Enabling Schema Validation ..................................................................................... 17

Samples Using the Properties ............................................................................................... 20Recommended Implementation of Properties ................................................................................... 20

4. Conformance Requirements .............................................................................................................. 215. XML Inclusions (XInclude) .............................................................................................................. 22

What is XML Inclusions (XInclude) .............................................................................................. 22Implementation 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 ...... 23JSR 206 Java API for XML Processing (JAXP) 1.3 Specification Version Information ............................. 23JSR 206 Java API for XML Processing (JAXP) 1.3 Implementation Version Information ......................... 24

7. Package javax.xml.parsers ................................................................................................................ 25Class DocumentBuilder ............................................................................................................... 25

Synopsis .......................................................................................................................... 25Members .......................................................................................................................... 26

Class DocumentBuilderFactory .................................................................................................... 30Synopsis .......................................................................................................................... 30Members .......................................................................................................................... 31

Class SAXParser ....................................................................................................................... 38Synopsis .......................................................................................................................... 39Members .......................................................................................................................... 40

Class SAXParserFactory ............................................................................................................. 47Synopsis .......................................................................................................................... 47

Final 1.0.0iv

Page 5: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Members .......................................................................................................................... 48Exception ParserConfigurationException ........................................................................................ 53

Synopsis .......................................................................................................................... 53Members .......................................................................................................................... 54

Error FactoryConfigurationError ................................................................................................... 54Synopsis .......................................................................................................................... 54Members .......................................................................................................................... 55

8. Package javax.xml.transform ............................................................................................................ 57Creating Objects ........................................................................................................................ 57

Specification of Inputs and Outputs ....................................................................................... 57Class OutputKeys ...................................................................................................................... 59

Synopsis .......................................................................................................................... 59Members .......................................................................................................................... 59

Class Transformer ...................................................................................................................... 62Synopsis .......................................................................................................................... 62Members .......................................................................................................................... 63

Class TransformerFactory ............................................................................................................ 68Synopsis .......................................................................................................................... 68Members .......................................................................................................................... 69

Interface ErrorListener ................................................................................................................ 74Synopsis .......................................................................................................................... 74Members .......................................................................................................................... 74

Interface Result ......................................................................................................................... 76Synopsis .......................................................................................................................... 76Members .......................................................................................................................... 76

Interface Source ......................................................................................................................... 77Synopsis .......................................................................................................................... 77Members .......................................................................................................................... 77

Interface SourceLocator .............................................................................................................. 78Synopsis .......................................................................................................................... 78Members .......................................................................................................................... 78

Interface Templates .................................................................................................................... 79Synopsis .......................................................................................................................... 79Members .......................................................................................................................... 79

Interface URIResolver ................................................................................................................ 80Synopsis .......................................................................................................................... 80Members .......................................................................................................................... 81

Exception TransformerConfigurationException ................................................................................ 81Synopsis .......................................................................................................................... 81Members .......................................................................................................................... 82

Exception TransformerException .................................................................................................. 83Synopsis .......................................................................................................................... 83Members .......................................................................................................................... 84

Error TransformerFactoryConfigurationError .................................................................................. 87Synopsis .......................................................................................................................... 88Members .......................................................................................................................... 88

9. Package javax.xml.transform.dom ...................................................................................................... 90Class DOMResult ...................................................................................................................... 90

Synopsis .......................................................................................................................... 90Members .......................................................................................................................... 91

Class DOMSource ..................................................................................................................... 95Synopsis .......................................................................................................................... 95Members .......................................................................................................................... 96

Interface DOMLocator ................................................................................................................ 97

Final 1.0.0v

JSR 206 Java API for XML Processing(JAXP) 1.3

Page 6: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Synopsis .......................................................................................................................... 97Members .......................................................................................................................... 97

10. Package javax.xml.transform.sax ..................................................................................................... 98Class SAXResult ....................................................................................................................... 98

Synopsis .......................................................................................................................... 99Members .......................................................................................................................... 99

Class SAXSource ..................................................................................................................... 101Synopsis ......................................................................................................................... 101Members ........................................................................................................................ 101

Class SAXTransformerFactory ................................................................................................... 104Synopsis ......................................................................................................................... 104Members ........................................................................................................................ 104

Interface TemplatesHandler ........................................................................................................ 107Synopsis ......................................................................................................................... 107Members ........................................................................................................................ 107

Interface TransformerHandler ..................................................................................................... 108Synopsis ......................................................................................................................... 108Members ........................................................................................................................ 108

11. Package javax.xml.transform.stream ............................................................................................... 110Class StreamResult ................................................................................................................... 110

Synopsis ......................................................................................................................... 110Members ........................................................................................................................ 111

Class StreamSource .................................................................................................................. 113Synopsis ......................................................................................................................... 113Members ........................................................................................................................ 114

12. Package javax.xml.namespace ....................................................................................................... 118Class QName .......................................................................................................................... 118

Synopsis ......................................................................................................................... 118Members ........................................................................................................................ 119

Interface NamespaceContext ...................................................................................................... 123Synopsis ......................................................................................................................... 123Members ........................................................................................................................ 124

13. Package javax.xml.xpath ............................................................................................................... 127XPath Overview ....................................................................................................................... 127

XPath Expressions ............................................................................................................ 127Class XPathConstants ............................................................................................................... 130

Synopsis ......................................................................................................................... 130Members ........................................................................................................................ 130

Class XPathFactory .................................................................................................................. 131Synopsis ......................................................................................................................... 131Members ........................................................................................................................ 132

Interface XPath ........................................................................................................................ 136Synopsis ......................................................................................................................... 137Members ........................................................................................................................ 138

Interface XPathExpression ......................................................................................................... 143Synopsis ......................................................................................................................... 143Members ........................................................................................................................ 144

Interface XPathFunction ............................................................................................................ 146Synopsis ......................................................................................................................... 146Members ........................................................................................................................ 147

Interface XPathFunctionResolver ................................................................................................ 147Synopsis ......................................................................................................................... 147Members ........................................................................................................................ 148

Interface XPathVariableResolver ................................................................................................. 148

Final 1.0.0vi

JSR 206 Java API for XML Processing(JAXP) 1.3

Page 7: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Synopsis ......................................................................................................................... 148Members ........................................................................................................................ 149

Exception XPathException ......................................................................................................... 149Synopsis ......................................................................................................................... 149Members ........................................................................................................................ 150

Exception XPathExpressionException .......................................................................................... 151Synopsis ......................................................................................................................... 151Members ........................................................................................................................ 151

Exception XPathFactoryConfigurationException ............................................................................ 152Synopsis ......................................................................................................................... 152Members ........................................................................................................................ 153

Exception XPathFunctionException ............................................................................................. 153Synopsis ......................................................................................................................... 153Members ........................................................................................................................ 154

14. Package javax.xml.validation ......................................................................................................... 155Class Schema .......................................................................................................................... 156

Synopsis ......................................................................................................................... 156Members ........................................................................................................................ 157

Class SchemaFactory ................................................................................................................ 157Schema Language ............................................................................................................ 158Synopsis ......................................................................................................................... 158Members ........................................................................................................................ 159

Class TypeInfoProvider ............................................................................................................. 169Synopsis ......................................................................................................................... 169Members ........................................................................................................................ 170

Class Validator ......................................................................................................................... 172Synopsis ......................................................................................................................... 173Members ........................................................................................................................ 174

Class ValidatorHandler .............................................................................................................. 180Recognized Properties and Features ..................................................................................... 181Synopsis ......................................................................................................................... 181Members ........................................................................................................................ 182

15. Package javax.xml.datatype ........................................................................................................... 189Class DatatypeConstants ............................................................................................................ 190

Synopsis ......................................................................................................................... 190Members ........................................................................................................................ 191

Class DatatypeConstants.Field .................................................................................................... 195Synopsis ......................................................................................................................... 195Members ........................................................................................................................ 195

Class DatatypeFactory ............................................................................................................... 195Synopsis ......................................................................................................................... 196Members ........................................................................................................................ 198

Class Duration ......................................................................................................................... 213Order relationship ............................................................................................................ 214Synopsis ......................................................................................................................... 214Members ........................................................................................................................ 216

Class XMLGregorianCalendar .................................................................................................... 227Synopsis ......................................................................................................................... 230Members ........................................................................................................................ 232

Exception DatatypeConfigurationException .................................................................................. 246Synopsis ......................................................................................................................... 246Members ........................................................................................................................ 247

16. Package javax.xml ....................................................................................................................... 248Class XMLConstants ................................................................................................................ 248

Final 1.0.0vii

JSR 206 Java API for XML Processing(JAXP) 1.3

Page 8: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Synopsis ......................................................................................................................... 248Members ........................................................................................................................ 248

17. Colophon ................................................................................................................................... 252Talk the Talk, Walk the Walk ...................................................................................................... 252

Final 1.0.0viii

JSR 206 Java API for XML Processing(JAXP) 1.3

Page 9: JSR 206 Java API for XML Processing (JAXP) 1 · 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

List of Tables6.1. JSR 206 Java API for XML Processing (JAXP) 1.3 Specification Version Information ............................... 2317.1. XML Usage Conventions ........................................................................................................... 252

Final 1.0.0ix

Page 10: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Final 1.0.0x

Page 11: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 1. OverviewWhat is XML?

XML is the meta language defined by the World Wide Web Consortium (W3C) that can be used to describe a broadrange of hierarchical mark up languages. It is a set of rules, guidelines, and conventions for describing structured datain a plain text, editable file. Using a text format instead of a binary format allows the programmer or even an end userto look at or utilize the data without relying on the program that produced it. However the primary producer and consumerof 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 "&lt;" and "&gt;" charactersand attributes are strings of the form ’name="value"’ that are inside of tags. While HTML specifies what each tagand attribute means, as well as their presentation attributes in a browser, XML uses tags only to delimit pieces of dataand leaves the interpretation of the data to the application that uses it. In other words, XML defines only the structureof 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 technologyis not entirely new. It is based on SGML (Standard Generalized Markup Language) which was developed in the early1980’s and became an ISO standard in 1986. SGML has been widely used for large documentation projects and thereis 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 andeasier to use.

XML-based documents can be used in a wide variety of applications including vertical markets, e-commerce, business-to-business communication, and enterprise application messaging.

XML and the Java™ PlatformIn many ways, XML and the Java Platform are a partnership made in heaven. XML defines a cross platform data formatand 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 byboth Java based programs and non-Java based programs.

About This SpecificationThis document describes the Java API for XML Processing, Version 1.3. This version of the specification introducesbasic 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 ofthis API and will provide an operational definition of the specification. A Technology Compatibility Kit (TCK) willalso be available that will verify whether an implementation of this specification is compliant. These are required asper 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

Final 1.0.01

Page 12: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Who Should Read This DocumentThis 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 technologiesand specifications on the part of the reader is assumed.

Report and ContactYour comments on this specification are welcome and appreciated. Without your comments, the specifications developedunder the auspices of the Java Community Process would not serve your needs as well. To comment on this specification,please send email to <[email protected]>.

You can stay current with Sun’s Java Platform related activities, as well as information on our <xml-interest>and <xml-announce> mailing lists, at our website [http://java.sun.com/xml/jaxp].

Development of This SpecificationThis specification was developed in accordance with the Java Community Process [http://www.jcp.org] 2.5. It wasdeveloped 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. Theseindividuals 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

Final 1.0.02

Overview

Page 13: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• Henry Zongaro, IBM

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

AcknowledgmentsMany individuals and companies have given their time and talents to make this specification, or the specifications thatthis 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 LaitJava 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 whomwork 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.

Final 1.0.03

Overview

Page 14: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 2. Endorsed SpecificationsThis specification endorses and builds upon several external specifications. Each specification endorsed by this documentis called out together with the exact version of the specification and its publicly accessible location. All of thesestandards 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], ExtensibleMarkup 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 thepurposes 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 amixture of versions may exist must consider carefully how serialization and transformation may interact withXML versions.

Namespaces in XMLThis specification supports Namespaces in XML 1.1. [http://www.w3.org/TR/xml-names11/], Namespaces in XML1.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 XML1.0 Errata, in their entirety for the purposes of defining Namespaces in XML in the APIs defined herein.

XML SchemaThis specification supports XML Schema Part 1: Structures [http://www.w3.org/TR/xmlschema-1/], XML SchemaPart 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, XMLSchema Part 2: Datatypes and XML Schema Part 2: Datatypes Errata in their entirety for the purposes of definingXML Schema in the APIs defined herein.

Final 1.0.04

Page 15: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 ofdefining 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 PathLanguage (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 W3CXML Activity [http://www.w3.org/XML/Activity].

This specification includes by reference XML Inclusions (XInclude) Version 1.0. in its entirety for the purposes ofdefining XInclude in the APIs defined herein.

Document Object Model (DOM) Level 3This 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

Final 1.0.05

Endorsed Specifications

Page 16: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Simple API for XML (SAX)This specification supports Simple API for XML (SAX) 2.0.2 (sax2r3) [http://sax.sourceforge.net/] and Simple APIfor 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) inthe APIs defined herein.

The API packages included by reference are:

• org.xml.sax

• org.xml.sax.ext

• org.xml.sax.helpers

Final 1.0.06

Endorsed Specifications

Page 17: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 3. Plugability LayerThe endorsed APIs provide broad and useful functionality. However, the use of a SAX or a DOM parser typically requiresknowledge of the specific implementation of the parser. Providing the functionality of the endorsed APIs in the JavaPlatform, 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 usedthrough the abstract javax.xml.parsers and javax.xml.transform API.

SAX PlugabilityThe SAX Plugability classes allow an application programmer to provide an implementation of theorg.xml.sax.DefaultHandler API to a SAXParser38 implementation and parse XML documents. As theparser 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 classto 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with the key beingthe system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XMLProcessing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist whenthe first attempt is made to read from it, no further attempts are made to check for its existence. It is not possibleto 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 ServicesAPI will look for the classname in the file META-INF/services/javax.xml.parsers.SAXParserFactory in jarsavailable 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 howthe user can resolve it.

The instance of SAXParserFactory47 can optionally be configured by the application programmer to provideparsers that are namespace aware, or validating, or both. These settings are made using the setNamespaceAwareand 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.

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

Final 1.0.07

Page 18: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 PlugabilityThe 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 newInstancemethod of the DocumentBuilderFactory30 class.

This method uses the following ordered lookup procedure to determine the DocumentBuilderFactory implementationclass 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with the key being

Final 1.0.08

Plugability Layer

Page 19: JSR 206 Java API for XML Processing (JAXP) 1 · 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

the system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XMLProcessing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist whenthe first attempt is made to read from it, no further attempts are made to check for its existence. It is not possibleto 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 ServicesAPI will look for the classname in the file META-INF/services/javax.xml.parsers.DocumentBuilderFactory in jarsavailable 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 problemand how the user can resolve it.

The instance of DocumentBuilderFactory30 can optionally be configured by the application programmer toprovide 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 aDocumentBuilder25 implementation instance from the factory. If the factory cannot provide a parser configuredas set by the application programmer, then a ParserConfigurationException is thrown.

Reliance on SAX APIThe 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.

ExamplesThe 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);

Final 1.0.09

Plugability Layer

Page 20: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.DocumentBuilderFactoryImpluser.parserApp

XSLT PlugabilityThe 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 programmerfirst 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 classto 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with the key beingthe system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XMLProcessing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist whenthe first attempt is made to read from it, no further attempts are made to check for its existence. It is not possibleto 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 ServicesAPI will look for the classname in the file META-INF/services/javax.xml.transform.TransformerFactory in jarsavailable 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 theproblem and how the user can resolve it.

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

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

Final 1.0.010

Plugability Layer

Page 21: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 transformationwhose 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 XSLTDocumentBuilder 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.xsl")) ? new DOMSource(xslInc2) : null;}});

// The TransformerFactory will call the anonymous URI// resolver set above when it encounters// &lt;xsl:include href="inc1/inc1.xsl"/&gt;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

Final 1.0.011

Plugability Layer

Page 22: JSR 206 Java API for XML Processing (JAXP) 1 · 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

// 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 StreamResult(System.out));}

The following example performs a transformation using DOM nodes as input for the TransformerFactory, as input forthe 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 XSLTDocumentBuilder 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:

Final 1.0.012

Plugability Layer

Page 23: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 ExampleContentHandler()));}

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);

Final 1.0.013

Plugability Layer

Page 24: JSR 206 Java API for XML Processing (JAXP) 1 · 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

// 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 parentorg.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:

Final 1.0.014

Plugability Layer

Page 25: JSR 206 Java API for XML Processing (JAXP) 1 · 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

// 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.TransformerFactoryImpluser.parserApp

XPath PlugabilityThe XPath Plugability classes allow an application programmer to obtain an XPath object that is based on a specificobject model implementation. In order to obtain an XPath object, a programmer first obtains an instance of theXPathFactory. 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with the key beingthe system property defined above. The jaxp.properties file is read only once by the JSR 206 Java™ API for XMLProcessing (JAXP) 1.3 implementation and it’s values are then cached for future use. If the file does not exist whenthe first attempt is made to read from it, no further attempts are made to check for its existence. It is not possibleto 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 ServicesAPI will look for the classname in the file META-INF/services/javax.xml.xpath.XPathFactory in jars available tothe 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 howthe user can resolve it.

Final 1.0.015

Plugability Layer

Page 26: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

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

// evaluate the XPath expression against the DocumentXPath 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, itis a property of the context in which it is evaluated.

Validation PlugabilityThe Validation Plugability classes allow an application programmer to obtain a Schema156 Object that is based ona specific schema language implementation. In order to obtain a Schema156 Object, a programmer first obtains aninstance of the SchemaFactory157. The SchemaFactory157 instance is obtained via the static newInstancemethod of the SchemaFactory157 Class.

This method uses the following ordered lookup procedure to determine the SchemaFactory157 implementationClass to load:

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

• Read the properties file $java.home/lib/jaxp.properties in the JRE directory. This configuration fileis in standard java.util.Properties format. $java.home/lib/jaxp.properties is read only onceby the JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation and it’s values are then cached forfuture use. If the file does not exist when the first attempt is made to read from it, no further attempts are made tocheck 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 (whereschemaLanguage is the parameter to newInstance), then its value is read as a Class name. The methodwill try to create a new instance of this Class by using the ClassLoader, and returns it if it is successfullycreated.

Final 1.0.016

Plugability Layer

Page 27: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• 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 forfile 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 platformdefault 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 SafetyImplementations of the SAXParser38, DocumentBuilder25, Transformer62, Validator172 and Validat 

orHandler180 abstract classes are not expected to be thread safe by this specification. This means that applicationprogrammers 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 anygiven SAXParser38, DocumentBuilder25, Transformer62, Validator172 or ValidatorHandler180 instance.

Configuration of a SAXParserFactory47, DocumentBuilderFactory30 TransformerFactory68 orSchemaFactory157 is also not expected to be thread safe. This means that an application programmer should notallow 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 beable 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 Validationjavax.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

Final 1.0.017

Plugability Layer

Page 28: JSR 206 Java API for XML Processing (JAXP) 1 · 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

setValidating(true)

javax.xml.parsers.SAXParser

The setProperty method in SAXParser must support the property strings defined below to indicate the schema languageand 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 theschema language specification. To be compliant with this version of the specification, the implementation must supportthe 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 languageonly. For example if an application sets the schemaLanguage property to XML Schemas then the parser must try tovalidate 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 tolocate schemas.

The schemaSource property lets the user set the schema(s) to validate against. If the target namespace of a schemaspecified using this property matches the target namespace of a schema occurring in schemaLocation attribute, theschema specified by the user using this property will be used and the instance document’s schemaLocation attributewill be effectively ignored. However if the target namespace of any schema specified using this property doesn’t matchthe target namespace of a schema occurring in the instance document, then the hint specified in the instance documentwill 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 onlywhen the schema language has the ability to assemble a schema at runtime. When an array of Objects is passed itis 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 exactlythe 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 theorg.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.

Final 1.0.018

Plugability Layer

Page 29: JSR 206 Java API for XML Processing (JAXP) 1 · 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

When setValidating is set to true and a schema language is set then the parser must validate against that schema languageonly. For example if an application sets the schema language property to XML Schemas the parser must try to validateagainst 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 orthe 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.

Schema file usedDocument Valid ated against

schema locationattribute presentin document?

schema sourceproperty set?

schema languageproperty set toXML Schemas?

Document hasDOCTYPE?

N/Aerror as per JAXP1.1 spec. Must

nononono

have a DOCTYPEdeclaration whenvalidation isturned on.

N/AError. Schema lan guage must be set.

yesnonono

N/AError schema lan guage must be set.

yes / noyesnono

schema files re ferred to using the

xml schemasyesnoyesyes / no

schema locationattributes presentin the instancedocument

schema file re ferred to in the

xml schemasnoyesyesyes / no

s c h e m a S o u r c eproperty

schema file re ferred to in the

xml schemasyesyesyesyes / no

schema sourceproperty, if the tar get namespacematches. Theschema file re ferred to in theschema locationattribute is ignoredonly if the targetn a m e s p a c ematches

DTD referred to inthe DOCTYPE

DTDyes / nononoyes

Final 1.0.019

Plugability Layer

Page 30: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Schema file usedDocument Valid ated against

schema locationattribute presentin document?

schema sourceproperty set?

schema languageproperty set toXML Schemas?

Document hasDOCTYPE?

N/AError. Schemasource cannot be

yes / noyesnoyes

set without settingthe schema lan guage.

Samples Using the PropertiesSax 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/2001/XMLSchema");sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "http://www.example.com/Report.xsd");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 PropertiesIt 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 alsothe way in which SAX defines feature and property strings.

Final 1.0.020

Plugability Layer

Page 31: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 4. Conformance RequirementsThis section describes the conformance requirements for implementations of this specification. Implementations thatare accessed via the APIs defined here must implement these constraints, without exception, to provide a predictableenvironment for application development and deployment.

Note that applications may provide non-conformant implementations that are able to support the plugability mechanismdefined in the specification, however the system default processor must meet the conformance requirements definedbelow.

All Implementations of JSR 206 Java™ API for XML Processing (JAXP) 1.3 Must Supportthe 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 XML 1.0[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) Version1.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) Version1.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 ObjectModel (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

Final 1.0.021

Page 32: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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. Specificationof the XML documents (infosets) to be merged and control over the merging process is expressedin 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 forXML 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 XPointerscheme or addressing mechanism, the error is signaled by throwing a java.lang.Exception for DOM processingand an org.xml.sax.SAXParseException for SAX processing

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

Final 1.0.022

Page 33: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 6. JSR 206 Java™ API for XMLProcessing (JAXP) 1.3 Specification andImplementation Version InformationJSR 206 Java™ API for XML Processing (JAXP) 1.3Specification Version Information

JSR 206 Java™ API for XML Processing (JAXP) 1.3 specification version information ismade 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 sequenceof positive decimal integers separated by "."'s and may have leading zeros. When version strings are compared themost 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 classesthat 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 informationwith the following values:

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

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

Sun Microsystems, Inc.Specification Vendor

1.3Specification Version

Sample META-INF/MANIFEST.MF entries to provide this information would be:

Specification-Title : JSR 206 Java™ API for XML Processing (JAXP) 1.3Specification-Vendor : Sun Microsystems, Inc.Specification-Version : 1.3

See the JAR File Specification, ${JAVA_HOME}/docs/guide/jar/jar.html, for detailed format information.

Final 1.0.023

Page 34: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

JSR 206 Java™ API for XML Processing (JAXP) 1.3 implementation version information ismade 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 implementationand does not have any particular syntax specified or expected by the Java runtime. It may be compared for equalitywith other package version strings used for this implementation by this vendor for this package. null is returnedif 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 informationwith reasonable values:

Implementation TitleImplementation VendorImplementation Version

Sample META-INF/MANIFEST.MF entries to provide this information would be:

Implementation-Title : My Implementation TitleImplementation-Vendor : My Implementation VendorImplementation-Version : My Implementation Version

See the JAR File Specification, ${JAVA_HOME}/docs/guide/jar/jar.html, for detailed format information.

Final 1.0.024

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

tion Version Information

Page 35: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 7. Package javax.xml.parsersProvides classes allowing the processing of XML documents. Two types of plugable parsers are supported:

• SAX (Simple API for XML)

• DOM (Document Object Model)

Class DocumentBuilderDefines 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 avariety 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 theimplementation communicate with the application using these existing APIs.

Synopsispublic 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();

Final 1.0.025

Page 36: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

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

Since 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.

Final 1.0.026

Package javax.xml.parsers

Page 37: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [Method setXInclude Aware(boolean)]

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. AnIllegalArgumentException 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;

Final 1.0.027

Package javax.xml.parsers

Page 38: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.Documentobject. 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.

Final 1.0.028

Package javax.xml.parsers

Page 39: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.Documentobject. 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. AnIllegalArgumentException 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 existingDocumentBuilder25s 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 EntityResolverand ErrorHandler.

Method setEntityResolver(EntityResolver)

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

Final 1.0.029

Package javax.xml.parsers

Page 40: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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. Settingthis 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 DocumentBuilderFactoryDefines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.

Synopsispublic 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();

Final 1.0.030

Package javax.xml.parsers

Page 41: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.031

Package javax.xml.parsers

Page 42: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 createscannot 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

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

Since 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 andappends 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();

Final 1.0.032

Package javax.xml.parsers

Page 43: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 elementcontent.

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

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

Since 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 configuredparameters.

Method newInstance()

static DocumentBuilderFactory newInstance();

Final 1.0.033

Package javax.xml.parsers

Page 44: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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. Thismethod 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with thekey being the system property defined above. The jaxp.properties file is read only once by the JAXP implementationand it's values are then cached for future use. If the file does not exist when the first attempt is made to read fromit, no further attempts are made to check for its existence. It is not possible to change the value of any property injaxp.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 ServicesAPI 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 configureand 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.

Final 1.0.034

Package javax.xml.parsers

Page 45: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 theadjacent (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 setto 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 createscannot 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.

Final 1.0.035

Package javax.xml.parsers

Page 46: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 enityexpansion limits and XML Schema constructs that would consume large amounts of resources. If XML processingis 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 possibleimplementation 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 XMLdocuments; false otherwise.

Specifies that the parsers created by this factory must eliminate whitespace in element content (sometimes knownloosely as 'ignorable whitespace') when parsing XML documents (see XML Rec 2.10). Note that only whitespacewhich is directly contained within element content that has an element only content model (see XML Rec 3.2.1) willbe eliminated. Due to reliance on the content model this setting requires the parser to be in validating mode. By defaultthe 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 thisis 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.

Final 1.0.036

Package javax.xml.parsers

Page 47: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

UnsupportedOperationEx ception

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

Since 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 documentsbefore it passes information down to the application.

When errors are found by the validator, the parser is responsible to report them to the user-specifiedorg.w3c.dom.DOMErrorHandler (or if the error handler is not set, ignore them or throw them), just like any other errorsfound by the parser itself. In other words, if the user-specified org.w3c.dom.DOMErrorHandler is set, it must receivethose 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/orthe http://java.sun.com/xml/jaxp/properties/schemaLanguage property in conjunction with ajavax.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 schemasare 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 thisis set to false.

Final 1.0.037

Package javax.xml.parsers

Page 48: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Note that "the validation" here means a validating parser [http://www.w3.org/TR/REC-xml#proc-types] as defined inthe XML recommendation. In other words, it essentially just controls the DTD validation. (except the legacy twoproperties 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 yourparser to be a non-validating parser by leaving the javax.xml.parsers.DocumentBuilderFactory.setValidating [ MethodsetValidating(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

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

Since 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 SAXParserDefines the API that wraps an org.xml.sax.XMLReader implementation class. In JAXP 1.0, this class wrapped theorg.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 thisclass 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 inputsources 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 noproperty 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 isdefined, a platform default will be used.

As the content is parsed by the underlying parser, methods of the given org.xml.sax.HandlerBase or theorg.xml.sax.helpers.DefaultHandler are called.

Final 1.0.038

Package javax.xml.parsers

Page 49: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Synopsispublic 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;

Final 1.0.039

Package javax.xml.parsers

Page 50: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [ MethodnewSAXParser()].

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;

Final 1.0.040

Package javax.xml.parsers

Page 51: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 theproperty.

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

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

Since 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.

Final 1.0.041

Package javax.xml.parsers

Page 52: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.042

Package javax.xml.parsers

Page 53: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 DefaultHandlerversion 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

Final 1.0.043

Package javax.xml.parsers

Page 54: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.HandlerBase. Use of theDefaultHandler 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.

Final 1.0.044

Package javax.xml.parsers

Page 55: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 inSAX 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 inSAX 2.0.

Final 1.0.045

Package javax.xml.parsers

Page 56: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 specifiedorg.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 specifiedorg.xml.sax.HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBaseclass has been deprecated in SAX 2.0

Method reset()

public void reset();

Final 1.0.046

Package javax.xml.parsers

Page 57: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 savingresources 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 theproperty.

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 featuresand properties can be found at http://sax.sourceforge.net/?selected=get-set [http://sax.sourceforge.net/?selected=get-set].

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

Synopsispublic SAXParserFactory {

protected SAXParserFactory();

static SAXParserFactory newInstance();

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

public void setNamespaceAware(boolean awareness);

Final 1.0.047

Package javax.xml.parsers

Page 58: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.SAXNotSupportedException;

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

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.SAXNotSupportedException;

Parameters

name The name of the property to be retrieved.

returns Value of the requested property.

Final 1.0.048

Package javax.xml.parsers

Page 59: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 theproperty.

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

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

Since 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

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

Since 1.5

Get state of XInclude processing.

Final 1.0.049

Package javax.xml.parsers

Page 60: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 methoduses 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with thekey being the system property defined above. The jaxp.properties file is read only once by the JAXP implementationand it's values are then cached for future use. If the file does not exist when the first attempt is made to read fromit, no further attempts are made to check for its existence. It is not possible to change the value of any property injaxp.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 ServicesAPI will look for a classname in the file META-INF/services/javax.xml.parsers.SAXParserFactoryin 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 andobtain 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;

Final 1.0.050

Package javax.xml.parsers

Page 61: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.SAXNotSupportedException;

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 theproperty.

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 featuresand 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 enityexpansion limits and XML Schema constructs that would consume large amounts of resources. If XML processingis 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 withoutregard to possible implementation limits.

Method setNamespaceAware(boolean)

public void setNamespaceAware(boolean awareness);

Final 1.0.051

Package javax.xml.parsers

Page 62: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thisis 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

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

Since 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 documentsbefore 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 foundby 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/orthe http://java.sun.com/xml/jaxp/properties/schemaLanguage property in conjunction with anon-null javax.xml.validation.Schema object. Such configuration will cause a org.xml.sax.SAXException exceptionwhen 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 schemasare 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);

Final 1.0.052

Package javax.xml.parsers

Page 63: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thisis set to false.

Note that "the validation" here means a validating parser [http://www.w3.org/TR/REC-xml#proc-types] as defined inthe XML recommendation. In other words, it essentially just controls the DTD validation. (except the legacy twoproperties 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 yourparser to be a non-validating parser by leaving the javax.xml.parsers.SAXParserFactory.setValidating [ MethodsetValidating(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

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

Since 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 ParserConfigurationExceptionIndicates a serious configuration error.

Synopsispublic ParserConfigurationException extends Exception {

public ParserConfigurationException();

Final 1.0.053

Package javax.xml.parsers

Page 64: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 FactoryConfigurationErrorThrown when a problem with configuration with the Parser Factories exists. This error will typically be thrown whenthe class of a parser factory specified in the system properties cannot be found or instantiated.

Synopsispublic FactoryConfigurationError extends Error {

public FactoryConfigurationError();

public FactoryConfigurationError(java.lang.String msg);

public FactoryConfigurationError(java.lang.Exception e);

Final 1.0.054

Package javax.xml.parsers

Page 65: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.055

Package javax.xml.parsers

Page 66: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 exceptionthen the message of that exception, if it exists will be returned. Else the name of the encapsulated exception will bereturned.

Final 1.0.056

Package javax.xml.parsers

Page 67: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 8. Package javax.xml.transformThis package defines the generic APIs for processing transformation instructions, and performing a transformationfrom source to result. These interfaces have no dependencies on SAX or the DOM standard, and try to make as fewassumptions as possible about the details of the source and result of a transformation. It achieves this by definingjavax.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. Theseinterfaces 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, Packagejavax.xml.transform.stream].

Creating ObjectsThe API allows a concrete javax.xml.transform.TransformerFactory [ Class TransformerFactory] object to be createdfrom the static function javax.xml.transform.TransformerFactory.newInstance [ Method newInstance()].

Specification of Inputs and OutputsThis 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 beused. 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]. Eachof 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 Resultobject is supported. For instance, to test if a DOMSource and a StreamResult is supported, you can apply the followingtest.

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 XMLobjects. 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 Namelike "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 dictionaryobject. Not having a string representation also makes it difficult to specify a namespaced identity outside the contextof an XML document.

In order to pass namespaced values to transformations, for instance when setting a property or a parameter on ajavax.xml.transform.Transformer [ Class Transformer] object, this specification defines that a String "qname" object

Final 1.0.057

Page 68: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 fora non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="ht tp://xyz.foo.com/yada/baz.html"/>, then the Qualified Name would be "{http://xyz.foo.com/yada/baz.html}foo". Notethat 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 referencedfrom the javax.xml.transform.OutputKeys [ Class OutputKeys] class. Other strings can be specified as well. If thetransformer does not recognize an output key, a java.lang.IllegalArgumentException is thrown, unless the key nameis namespace qualified [#qname-delimiter]. Output key names that are namespace qualified are always allowed, althoughthey 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 [ MethodnewTransformer()] method with no arguments. This method creates a Transformer that effectively copies the sourceto the result. This method may be used to create a DOM from SAX events or to create an XML or HTML stream froma 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 typicallybe thrown when the transformation factory class specified with the "javax.xml.transform.TransformerFactory" systemproperty cannot be found or instantiated.

A javax.xml.transform.TransformerConfigurationException [ Exception TransformerConfigurationException] maybe thrown if for any reason a Transformer can not be created. A TransformerConfigurationException may be thrownif 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 occursduring the course of a transformation. A transformer exception may wrap another exception, and if any of thejavax.xml.transform.TransformerException.printStackTrace [ Method printStackTrace()] methods are called on it, itwill produce a list of stack dumps, starting from the most recent. The transformer exception also provides ajavax.xml.transform.SourceLocator [ Interface SourceLocator] object which indicates where in the source tree ortransformation 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 locationstring.

Transformation warnings and errors are sent to an javax.xml.transform.ErrorListener [ Interface ErrorListener], atwhich point the application may decide to report the error or warning, and may decide to throw an Exception fora 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

Final 1.0.058

Package javax.xml.transform

Page 69: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 ErrorListeneron both objects will always be valid and non- null, whether set by the application or a default implementation providedby 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 beresolved 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 [ Methodresolve(java.lang.String, java.lang.String)], and use this class to set the URI resolution for the transformation instructionsor 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 URIfound in the stylesheet instructions or built as part of the transformation process, and the base URI against which thefirst argument will be made absolute if the absolute URI is required. The returned javax.xml.transform.Source [ InterfaceSource] object must be usable by the transformer, as specified in its implemented features.

Class OutputKeysProvides string constants that can be used to set output properties for a Transformer, or to retrieve output propertiesfrom a Transformer or Templates object.

All the fields in this class are read-only.

Synopsispublic OutputKeys {}

See Also section 16 of the XSL Transformations (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

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 (XSLT) W3C Recommendation.[http://www.w3.org/TR/xslt#output]

cdata-section-elements = expanded names expanded names.

Final 1.0.059

Package javax.xml.transform

Page 70: JSR 206 Java API for XML Processing (JAXP) 1 · 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

cdata-section-elements specifies a whitespace delimited list of the names of elements whose text node childrenshould be output using CDATA sections. Note that these names must use the format described in the section QualfiedName 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 (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

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 (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

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 <!DOCTYPE should be the name of the first element. If doctype-public property is also specified, then the xml output method should output PUBLIC followed by the public identifierand then the system identifier; otherwise, it should output SYSTEM followed by the system identifier. The internalsubset should be empty. The value of the doctype-public property should be ignored unless the doctype-system propertyis specified.

If the doctype-public or doctype-system properties are specified, then the html output method should output a documenttype declaration immediately before the first element. The name following <!DOCTYPE should be HTML or html. Ifthe doctype-public property is specified, then the output method should output PUBLIC followed by the specifiedpublic identifier; if the doctype-system property is also specified, it should also output the specified system identifierfollowing the public identifier. If the doctype-system property is specified but the doctype-public property is not specified,then the output method should output SYSTEM followed by the specified system identifier.

doctype-system specifies the system identifier to be used in the document type declaration.

Field ENCODING

  static java.lang.String ENCODING ;

See Also section 16 of the XSL Transformations (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

encoding = string string.

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

Final 1.0.060

Package javax.xml.transform

Page 71: JSR 206 Java API for XML Processing (JAXP) 1 · 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

contain characters in the range #x21 to #x7E (i.e., printable ASCII characters). The value should either be a charsetregistered 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 (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

indent = "yes" | "no".

indent specifies whether the Transformer may add additional whitespace when outputting the result tree; the valuemust be yes or no.

Field MEDIA_TYPE

  static java.lang.String MEDIA_TYPE ;

See Also s ection 16 of the XSL Transformations (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

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, acharset 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 (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

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. Othernon-namespaced values may be used, such as "xhtml", but, if accepted, the handling of such values is implementationdefined. 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 (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

omit-xml-declaration = "yes" | "no".

omit-xml-declaration specifies whether the XSLT processor should output an XML declaration; the valuemust be yes or no.

Final 1.0.061

Package javax.xml.transform

Page 72: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Field STANDALONE

  static java.lang.String STANDALONE ;

See Also section 16 of the XSL Transformations (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

standalone = "yes" | "no".

standalone specifies whether the Transformer should output a standalone document declaration; the value mustbe yes or no.

Field VERSION

  static java.lang.String VERSION ;

See Also section 16 of the XSL Transformations (XSLT) W3C Recommendation[http://www.w3.org/TR/xslt#output]

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 resulttree. The default value for the xml output method is 1.0. When the output method is "html", the version value indicatesthe version of the HTML. The default value for the xml output method is 4.0, which specifies that the result should beoutput as HTML conforming to the HTML 4.0 Recommendation [HTML]. If the output method is "text", the versionproperty is ignored.

Class TransformerAn 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 sourcesand 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 usedconcurrently by different threads.

A Transformer62 may be used multiple times. Parameters and output properties are preserved across transformations.

Synopsispublic Transformer {

protected Transformer();

public void reset();

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

Final 1.0.062

Package javax.xml.transform

Page 73: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.063

Package javax.xml.transform

Page 74: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 stylesheetshould be in the base Properties list, while the XSLT default properties that were not specifically set should be thedefault Properties list. Thus, getOutputProperties().getProperty(String key) will obtain any property in that was set byjavax.xml.transform.Transformer.setOutputProperty [ Method setOutputProperty(java.lang.String, java.lang.String)],javax.xml.transform.Transformer.setOutputProperties [ Method setOutputProperties(java.util.Properties)], in thestylesheet, or the default properties, while getOutputProperties().get(String key) will only retrieve properties that wereexplicitly 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 notreturned. 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 If the property is not supported.

See Also 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 withsetOutputProperty, or it may be a property specified in the stylesheet.

Final 1.0.064

Package javax.xml.transform

Page 75: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 evaluatedduring 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 [ MethodnewTransformer()]. 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 isguaranteed 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.

Final 1.0.065

Package javax.xml.transform

Page 76: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thetransformation.

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 withxsl:output.

If argument to this function is null, any properties previously set are removed, and the value will revert to the valuedefined in the templates object.

Pass a qualified property key name as a two-part string, the namespace URI enclosed in curly braces ({}), followedby the local name. If the name has a null URL, the String only contain the local name. An application can safely checkfor a non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="ht tp://xyz.foo.com/yada/baz.html"/>, then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Notethat no prefix is used.

An IllegalArgumentException is thrown if any of the argument keys are not recognized and are not namespacequalified.

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 If the property is not supported, and is not qualified with a namespace.

See Also 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 thelocal name. If the name has a null URL, the String only contain the local name. An application can safely check for anon-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="ht tp://xyz.foo.com/yada/baz.html"/>, then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Notethat no prefix is used.

Final 1.0.066

Package javax.xml.transform

Page 77: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 objectcoersion 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 localname. 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 <xyz:foo xmlns:xyz="ht tp://xyz.foo.com/yada/baz.html"/>, then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Notethat 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.

Final 1.0.067

Package javax.xml.transform

Page 78: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 theTransformerFactory68 in effect when the Transformer62 was instantiated and any modifications made to theTransformer62 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 alwaysan empty Result.

Class TransformerFactoryA TransformerFactory instance can be used to create javax.xml.transform.Transformer [ Class Transformer] andjavax.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 abstractclass. If the property is not defined, a platform default is be used.

Synopsispublic 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);

Final 1.0.068

Package javax.xml.transform

Page 79: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

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

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

Final 1.0.069

Package javax.xml.transform

Page 80: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 severalstylesheets, 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 IllegalArgumentExceptionis 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 returnedif this TransformerFactory68 or the Transformer62s or Templates it creates cannot support the feature. Itis 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, orxsl:include.

Method newInstance()

static TransformerFactory newInstance()    throws TransformerFactoryConfigurationError;

Final 1.0.070

Package javax.xml.transform

Page 81: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 Thismethod uses the following ordered lookup procedure to determine the TransformerFactory68 implementationclass 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 standardjava.util.Properties format and contains the fully qualified name of the implementation class with thekey being the system property defined above. The jaxp.properties file is read only once by the JAXP implementationand it's values are then cached for future use. If the file does not exist when the first attempt is made to read fromit, no further attempts are made to check for its existence. It is not possible to change the value of any property injaxp.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 ServicesAPI 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 andobtain 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 objectmay then be used concurrently across multiple threads. Creating a Templates object allows the TransformerFactory todo detailed performance optimization of transformation instructions, without penalizing runtime transformation.

Method newTransformer()

public Transformer abstract newTransformer()    throws TransformerConfigurationException;

Final 1.0.071

Package javax.xml.transform

Page 82: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 includeDOMSource [ Class DOMSource], SAXSource [ Class SAXSource], and StreamSource [ ClassStreamSource].

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

Exceptions

TransformerConfigura tionException

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

See Also 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 XSLTransformations (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 bydifferent 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 tobe an option that the implementation provides. An IllegalArgumentException is thrown if the underlyingimplementation doesn't recognize the attribute.

Method setErrorListener(ErrorListener)

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

Final 1.0.072

Package javax.xml.transform

Page 83: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 ErrorListenerlistener 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 createscannot 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 foran 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 securefashion as defined by the implementation. Examples include resolving user defined style sheets and functions. IfXML 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 possibleimplementation limits.

Method setURIResolver(URIResolver)

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

Parameters

resolver An object that implements the URIResolver interface, or null.

Final 1.0.073

Package javax.xml.transform

Page 84: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

Interface ErrorListenerTo provide customized error handling, implement this interface and use the setErrorListener method to registeran 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 whichreports all warnings and errors to System.err and does not throw any Exceptions. Applications are stronglyencouraged 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 tothe application to decide whether to throw an Exception for different types of errors and warnings. Note howeverthat 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.

Synopsisimplements 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.

Final 1.0.074

Package javax.xml.transform

Page 85: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

javax.xml.transform.Trans formerException

if the application chooses to discontinue the transformation.

See Also 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 bepossible 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

if the application chooses to discontinue the transformation.

See Also 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 shouldstill be possible for the application to process the document through to the end if no other errors are encountered, butthere 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

if the application chooses to discontinue the transformation.

See Also 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 orfatal errors. The default behaviour is to take no action.

Final 1.0.075

Package javax.xml.transform

Page 86: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

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

Synopsisimplements 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. Thisensures that the output is well-formed XML. However, it is sometimes convenient to be able to produce output that isalmost, but not quite well-formed XML; for example, the output may include ill-formed sections that will be transformedinto 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_ESCAPINGinserted 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 havingreceived a PI_DISABLE_OUTPUT_ESCAPING processing instruction.

Method getSystemId()

public String getSystemId();

Final 1.0.076

Package javax.xml.transform

Page 87: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 provideone, however, for use in error messages and warnings, or to resolve relative output identifiers.

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

Synopsisimplements 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.

Final 1.0.077

Package javax.xml.transform

Page 88: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

Interface SourceLocatorThis interface is primarily for the purposes of reporting where an error occurred in the XML source or transformationinstructions.

Synopsisimplements 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 isnot 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 themarkup 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 isnot intended to provide sufficient information to edit the character content of the original XML document.

Final 1.0.078

Package javax.xml.transform

Page 89: JSR 206 Java API for XML Processing (JAXP) 1 · 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

The return value is an approximation of the line number in the document entity or external parsed entity where themarkup 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 markupthat 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 markupthat triggered the event appears.

If the system identifier is a URL, the parser must resolve it fully before passing it to the application.

Interface TemplatesAn 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 multipletimes in a given session.

Synopsisimplements public Templates {

public Transformer newTransformer()    throws TransformerConfigurationException;

public Properties getOutputProperties();

}

Inheritance Path

javax.xml.transform.Templates

Members

Method getOutputProperties()

public Properties getOutputProperties();

Final 1.0.079

Package javax.xml.transform

Page 90: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Get the properties corresponding to the effective xsl:output element. The object returned will be a clone of the internalvalues. 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 defaultproperties 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 baseProperties list, while the XSLT default properties that were not specifically set should be in the "default" Propertieslist. Thus, getOutputProperties().getProperty(String key) will obtain any property in that was set by the stylesheet, orthe default properties, while getOutputProperties().get(String key) will only retrieve properties that were explicitly setin the stylesheet.

For XSLT, Attribute Value Templates [http://www.w3.org/TR/xslt#attribute-value-templates] attribute values will bereturned unexpanded (since there is no context at this point). The namespace prefixes inside Attribute Value Templateswill 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 URIResolverAn 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.

Synopsisimplements public URIResolver {

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

}

Inheritance Path

javax.xml.transform.URIResolver

Final 1.0.080

Package javax.xml.transform

Page 91: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 theURI 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 TransformerConfigurationExceptionIndicates a serious configuration error.

Synopsispublic 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

|

Final 1.0.081

Package javax.xml.transform

Page 92: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 DocumentHandlercallback.

Constructor TransformerConfigurationException(String, SourceLocator,Throwable)

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

Final 1.0.082

Package javax.xml.transform

Page 93: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 detailmessage.

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 TransformerExceptionThis class specifies an exceptional condition that occured during the transformation process.

Synopsispublic 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);

Final 1.0.083

Package javax.xml.transform

Page 94: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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);

Final 1.0.084

Package javax.xml.transform

Page 95: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 DocumentHandlercallback.

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();

Final 1.0.085

Package javax.xml.transform

Page 96: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Returns the cause of this throwable or null if the cause is nonexistent or unknown. (The cause is the throwable thatcaused 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)], orthis method has already been called on this throwable.

Final 1.0.086

Package javax.xml.transform

Page 97: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable toget thrown.)

This method can be called at most once. It is generally called from within the constructor, or immediately after creatingthe 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 asthis 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 asthis 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 asthis 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 TransformerFactoryConfigurationErrorThrown when a problem with configuration with the Transformer Factories exists. This error will typically be thrownwhen the class of a transformation factory specified in the system properties cannot be found or instantiated.

Final 1.0.087

Package javax.xml.transform

Page 98: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Synopsispublic 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);

Final 1.0.088

Package javax.xml.transform

Page 99: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 detailmessage.

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 exceptionthen the message of that exception will be returned.

Final 1.0.089

Package javax.xml.transform

Page 100: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 9. Package javax.xml.transform.domThis package implements DOM-specific transformation APIs.

The javax.xml.transform.dom.DOMSource [ Class DOMSource] class allows the client of the implementation of thisAPI to specify a DOM org.w3c.dom.Node as the source of the input tree. The model of how the Transformer dealswith the DOM tree in terms of mismatches with the XSLT data model [http://www.w3.org/TR/xslt#data-model] orother data models is beyond the scope of this document. Any of the nodes derived from org.w3c.dom.Node are legalinput.

The javax.xml.transform.dom.DOMResult [ Class DOMResult] class allows a org.w3c.dom.Node to be specified towhich result DOM nodes will be appended. If an output node is not specified, the transformer will usejavax.xml.parsers.DocumentBuilder#newDocument to create an output org.w3c.dom.Document node. If a node isspecified, 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 resultis a org.w3c.dom.Document, the output of the transformation must have a single element root to set as the documentelement.

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 thejavax.xml.transform.TransformerException.getLocator [ Method getLocator()] method. The implementation has noresponsibility to use a DOMLocator instead of a javax.xml.transform.SourceLocator [ Interface SourceLocator] (thoughline numbers and the like do not make much sense for a DOM), so the result of getLocator must always be tested withan instanceof.

Class DOMResultActs 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 thetransformation, which may be retrieved with javax.xml.transform.dom.DOMResult.getNode [ Method getNode()].

Synopsispublic 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();

Final 1.0.090

Page 101: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 aorg.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.

Final 1.0.091

Package javax.xml.transform.dom

Page 102: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 insertedbefore.

In practice, node and nextSibling should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragmentnode, 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 isnot a sibling of node, then an IllegalArgumentException is thrown. If node is null and nextSiblingis not null, then an IllegalArgumentException is thrown. If nextSibling is null, then the behavior isthe same as calling javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node)], i.e. appendthe 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 insertedbefore and the specified System ID.

In practice, node and nextSibling should be a org.w3c.dom.Document node, a org.w3c.dom.DocumentFragmentnode, 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 isnot a sibling of node, then an IllegalArgumentException is thrown. If node is null and nextSiblingis not null, then an IllegalArgumentException is thrown. If nextSibling is null, then the behavior is

Final 1.0.092

Package javax.xml.transform.dom

Page 103: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 aorg.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 whenpassed 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 thenode 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.

Final 1.0.093

Package javax.xml.transform.dom

Page 104: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 isnot a descendant of node, then an IllegalArgumentException is thrown. If node is null and nextSiblingis not null, then an IllegalStateException is thrown. If nextSibling is null, then the behavior is thesame as calling javax.xml.transform.dom.DOMResult [ Constructor DOMResult(org.w3c.dom.Node)], i.e. append theresult 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 aorg.w3c.dom.Element node. In other words, a node that accepts children.

Final 1.0.094

Package javax.xml.transform.dom

Page 105: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 DOMSourceActs 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 namespace-aware parser may result in errors. Parsers can be made namespace aware by calling javax.xml.parsers.DocumentBuild erFactory#setNamespaceAware(boolean awareness).

Synopsispublic 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

Final 1.0.095

Package javax.xml.transform.dom

Page 106: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Members

Constructor DOMSource()

public DOMSource();

See Also javax.xml.transform.Transformer.transform [Method transform(javax.xml.transform.Source,javax.xml.transform.Result)]

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 anempty 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 isdone 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 passedthis 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.

Final 1.0.096

Package javax.xml.transform.dom

Page 107: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 DOMLocatorIndicates the position of a node in a source DOM, intended primarily for error reporting. To use a DOMLocator, thereceiver of an error must downcast the javax.xml.transform.SourceLocator [ Interface SourceLocator] object returnedby an exception. A javax.xml.transform.Transformer [ Class Transformer] may use this object for purposes other thanerror reporting, for instance, to indicate the source node that originated a result node.

Synopsisimplements 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.

Final 1.0.097

Package javax.xml.transform.dom

Page 108: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 10. Package javax.xml.transform.saxThis package implements SAX2-specific transformation APIs. It provides classes which allow input fromorg.xml.sax.ContentHandler events, and also classes that produce org.xml.sax.ContentHandler events. It also providesmethods to set the input source as an org.xml.sax.XMLReader, or to use a org.xml.sax.InputSource as the source. Italso 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.XMLReaderto 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.ContentHandlerto 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 [ InterfaceTransformerHandler], and org.xml.sax.XMLReader instances.

To obtain a javax.xml.transform.sax.SAXTransformerFactory [ Class SAXTransformerFactory], the caller must castthe 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 transformationto be created from SAX2 parse events, which is a "push" model rather than the "pull" model that normally occurs fora transformation. Normal parse events are received through the org.xml.sax.ContentHandler interface, lexical eventssuch as startCDATA and endCDATA are received through the org.xml.sax.ext.LexicalHandler interface, and eventsthat 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 [ FieldPI_DISABLE_OUTPUT_ESCAPING] and javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING [ FieldPI_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 fromjavax.xml.transform.sax.TransformerHandler.getTransformer [ Method getTransformer()], and the methods invokedfrom that reference.

The javax.xml.transform.sax.TemplatesHandler [ Interface TemplatesHandler] interface allows the creation ofjavax.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 whichrelative 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 parentorg.xml.sax.XMLReader, and the final transformation is caused by invoking org.xml.sax.XMLReader.parse on the finalreader in the chain.

Class SAXResultActs as an holder for a transformation Result.

Final 1.0.098

Page 109: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Synopsispublic 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 passedthis value as an argument, the Transformer supports Result output of this type.

Final 1.0.099

Package javax.xml.transform.sax

Page 110: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 bythe 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.

Final 1.0.0100

Package javax.xml.transform.sax

Page 111: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Class SAXSourceActs as an holder for SAX-style Source.

Note that XSLT requires namespace support. Attempting to transform an input source that is not generated with anamespace-aware parser may result in errors. Parsers can be made namespace aware by calling the javax.xml.pars ers.SAXParserFactory#setNamespaceAware(boolean awareness) method.

Synopsispublic 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 [Method transform(javax.xml.transform.Source,javax.xml.transform.Result)]

Final 1.0.0101

Package javax.xml.transform.sax

Page 112: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 methodof 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 viaorg.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 readerparse 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 setitself 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 passedthis 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.

Final 1.0.0102

Package javax.xml.transform.sax

Page 113: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 inputsource, 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, sincethe application can use it to resolve relative URIs and can include it in error messages and warnings (the parser willattempt 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.

Final 1.0.0103

Package javax.xml.transform.sax

Page 114: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Class SAXTransformerFactoryThis 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, itshould use a URIResolver to return the SAXSource which provides (with getXMLReader) a reference to the XMLReader.

Synopsispublic 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 templates)    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.

Final 1.0.0104

Package javax.xml.transform.sax

Page 115: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Field FEATURE

  static java.lang.String FEATURE ;

If javax.xml.transform.TransformerFactory.getFeature [ Method getFeature(java.lang.String)] returns true when passedthis 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 passedthis 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 [ MethodnewXMLFilter(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 isdefined 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.

Final 1.0.0105

Package javax.xml.transform.sax

Page 116: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 transformationinstructions specified by the argument.

Method newTransformerHandler(Templates)

public TransformerHandler abstract newTransformerHandler(javax.xml.transform.Templates templates)    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 Templatesargument.

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.

Final 1.0.0106

Package javax.xml.transform.sax

Page 117: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 TemplatesHandlerA SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into aTemplates object.

Note that TemplatesHandler does not need to implement LexicalHandler.

Synopsisimplements 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 createsa Templates object, which the caller can get once the SAX events have been completed.

Method setSystemId(String)

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

Final 1.0.0107

Package javax.xml.transform.sax

Page 118: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 resolverelative URIs in the stylesheet. This must be called before the startDocument event.

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

Synopsisimplements 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.

Final 1.0.0108

Package javax.xml.transform.sax

Page 119: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0109

Package javax.xml.transform.sax

Page 120: JSR 206 Java API for XML Processing (JAXP) 1 · 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

C h a p t e r   1 1 .   P a c k a g ejavax.xml.transform.stream

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

The javax.xml.transform.stream.StreamSource [ Class StreamSource] class provides methods for specifyingjava.io.InputStream input, java.io.Reader input, and URL input in the form of strings. Even if an input stream orreader 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 relativeURIs. The public identifier is always optional: if the application writer includes one, it will be provided as part of thejavax.xml.transform.SourceLocator [ Interface SourceLocator] information.

The javax.xml.transform.stream.StreamResult [ Class StreamResult] class provides methods for specifyingjava.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 andwriters already have the encoding established to and from the internal Unicode format. However, there are times whenit is useful to write to a character stream, such as when using a StringWriter in order to write to a String, or in the caseof reading source XML from a StringReader.

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

Synopsispublic 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();

Final 1.0.0110

Page 121: JSR 206 Java API for XML Processing (JAXP) 1 · 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

}

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 thetransformer 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);

Final 1.0.0111

Package javax.xml.transform.stream

Page 122: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thetransformer may use instructions contained in the transformation instructions to control the encoding. However, thereare 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 passedthis 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 transformermay 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.

Final 1.0.0112

Package javax.xml.transform.stream

Page 123: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

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 valueas 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 transformermay use instructions contained in the transformation instructions to control the encoding. However, there are timeswhen it is useful to write to a writer, such as when using a StringWriter.

Class StreamSourceActs 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 instancesmay only be used once.

Synopsispublic 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);

Final 1.0.0113

Package javax.xml.transform.stream

Page 124: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [Method transform(javax.xml.transform.Source,javax.xml.transform.Result)]

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 anempty 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.

Final 1.0.0114

Package javax.xml.transform.stream

Page 125: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XMLparser 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 URIreferences 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 XMLparser 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 theXML parser can resolve character encoding specified by the XML declaration. However, in many cases the encodingof 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.

Final 1.0.0115

Package javax.xml.transform.stream

Page 126: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Construct a StreamSource from a character reader. Normally, a stream should be used rather than a reader, so that theXML parser may resolve character encoding specified by the XML declaration. However, in many cases the encodingof 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 passedthis 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.

Final 1.0.0116

Package javax.xml.transform.stream

Page 127: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Set the byte stream to be used as input. Normally, a stream should be used rather than a reader, so that the XML parsercan 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 URLreferences 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 locationinformation.

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 parsercan resolve character encoding specified by the XML declaration. However, in many cases the encoding of the inputstream 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, sincethe application can use it to resolve relative URIs and can include it in error messages and warnings (the parser willattempt to open a connection to the URI only if there is no byte stream or character stream specified).

Final 1.0.0117

Package javax.xml.transform.stream

Page 128: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 12. Package javax.xml.namespaceXML 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 QNameQName118 represents a qualified name as defined in the XML specifications: XML Schema Part2: Datatypes specification[h t tp : / /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].

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 isNOT 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.

Synopsispublic 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();

Final 1.0.0118

Page 129: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 inXML 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 local part of the QName118

See Also QName(String namespaceURI, String localPart) [Constructor QName(java.lang.String,java.lang.String)], QName(String namespaceURI, String localPart, String prefix) [ConstructorQName(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 preservecompatible 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 duringthe construction of a QName118 helps prevent hard to diagnosis XML validity errors. The constructors QName(StringnamespaceURI, String localPart) [Constructor QName(java.lang.String, java.lang.String)] andjavax.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 inNamespaces in XML [http://www.w3.org/TR/REC-xml-names/].

Final 1.0.0119

Package javax.xml.namespace

Page 130: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 definedNamespace 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 preservecompatible 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 notvalidated 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 definedNamespace 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 preservecompatible behavior with QName 1.0.

Final 1.0.0120

Package javax.xml.namespace

Page 131: JSR 206 Java API for XML Processing (JAXP) 1 · 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

If the prefix is null, an IllegalArgumentException is thrown. Use XMLConstants.DEFAULT_NS_PREFIXto 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 prefixare not validated as a NCName [http://www.w3.org/TR/REC-xml-names/#NT-NCName] as specified in Namespacesin 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 usesString.equals() to check equality of the Namespace URI and local part. The prefix is NOT used to determineequality.

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 assigneda 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.

Final 1.0.0121

Package javax.xml.namespace

Page 132: JSR 206 Java API for XML Processing (JAXP) 1 · 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

The hash code is calculated using both the Namespace URI and the local part of the QName118. The prefix is NOT usedto 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: "{" + NamespaceURI + "}" + local part. If the Namespace URI .equals(XMLConstants.NULL_NS_URI), only the local part isreturned. 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: "{" + NamespaceURI + "}" + local part. If the Namespace URI .equals(XMLConstants.NULL_NS_URI), only the local partshould 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 notvalidated 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/].

Final 1.0.0122

Package javax.xml.namespace

Page 133: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Interface NamespaceContextInterface 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: <element xmlns:prefix="http://Namespace-name-URI">

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 thesame Namespace URI. e.g.

<element xmlns:prefix1="http://Namespace-name-URI"xmlns:prefix2="http://Namespace-name-URI">

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.

<parent xmlns:prefix1="http://Namespace-name-URI"><child xmlns:prefix2="http://Namespace-name-URI">...</child></parent>

A prefix can only be bound to a single Namespace URI in the current scope.

Synopsisimplements 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 $

Final 1.0.0123

Package javax.xml.namespace

Page 134: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 allpossible prefix values:

getNamespaceURI(prefix) return value for specified prefixes

Namespace URI return valueprefix parameter

default Namespace URI in the current scope or XMLCon stants.NULL_NS_URI("") when there is no defaultNamespace URI in the current scope

DEFAULT_NS_PREFIX ("")

Namespace URI bound to prefix in current scopebound prefix

XMLConstants.NULL_NS_URI("")unbound prefix

XMLConstants.XML_NS_URI ("ht tp://www.w3.org/XML/1998/namespace")

XMLConstants.XML_NS_PREFIX ("xml")

XMLConstants.XMLNS_ATTRIBUTE_NS_URI ("ht tp://www.w3.org/2000/xmlns/")

XMLConstants.XMLNS_ATTRIBUTE ("xmlns")

IllegalArgumentException is thrownnull

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

Final 1.0.0124

Package javax.xml.namespace

Page 135: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 NamespaceURI values:

getPrefix(namespaceURI) return value for specified Namespace URIs

prefix value returnedNamespace URI parameter

XMLConstants.DEFAULT_NS_PREFIX ("")<default Namespace URI>

prefix bound to Namespace URI in the current scope, ifmultiple prefixes are bound to the Namespace URI in the

bound Namespace URI

current scope, a single arbitrary prefix, whose choice isimplementation dependent, is returned

nullunbound Namespace URI

XMLConstants.XML_NS_PREFIX ("xml")XMLConstants.XML_NS_URI ("ht tp://www.w3.org/XML/1998/namespace")

XMLConstants.XMLNS_ATTRIBUTE ("xmlns")XMLConstants.XMLNS_ATTRIBUTE_NS_URI ("ht tp://www.w3.org/2000/xmlns/")

IllegalArgumentException is thrownnull

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 NamespaceURI values:

getPrefixes(namespaceURI) return value for specified Namespace URIs

prefixes value returnedNamespace URI parameter

Iterator over prefixes bound to Namespace URI in thecurrent scope in an arbitrary, implementation dependent,order

bound Namespace URI, including the <default NamespaceURI>

empty Iteratorunbound Namespace URI

Iterator with one element set to XMLCon stants.XML_NS_PREFIX ("xml")

XMLConstants.XML_NS_URI ("ht tp://www.w3.org/XML/1998/namespace")

Final 1.0.0125

Package javax.xml.namespace

Page 136: JSR 206 Java API for XML Processing (JAXP) 1 · 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

getPrefixes(namespaceURI) return value for specified Namespace URIs

prefixes value returnedNamespace URI parameter

Iterator with one element set to XMLConstants.XM LNS_ATTRIBUTE ("xmlns")

XMLConstants.XMLNS_ATTRIBUTE_NS_URI ("ht tp://www.w3.org/2000/xmlns/")

IllegalArgumentException is thrownnull

Final 1.0.0126

Package javax.xml.namespace

Page 137: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 13. Package javax.xml.xpathThis package provides an object-model neutral API for the evaluation of XPath expressions and access to the evaluationenvironment.

The following XML standards apply:

• XML Path Language (XPath) Version 1.0 [http://www.w3.org/TR/xpath]

XPath OverviewThe XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also providesrules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value. XPathis 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 becomepopular as a stand-alone language, as a single XPath expression can be used to replace many lines of DOM API code.

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

The following is an example of a simple XPath expression:

/foo/bar

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

<foo><bar/></foo>

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

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

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

Final 1.0.0127

Page 138: JSR 206 Java API for XML Processing (JAXP) 1 · 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

//bar

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

/foo/*

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

DescriptionLocation Path

Selects the attribute id of the <bar> element/foo/bar/@id

Selects the text nodes of the <bar> element. No distinctionis made between escaped and non-escaped character data.

/foo/bar/text()

Selects all comment nodes contained in the <bar> ele ment.

/foo/bar/comment()

Selects all processing-instruction nodes contained in the<bar> element.

/foo/bar/processing-instruction()

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

//foo[@include='true']

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

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

Using the XPath API

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

XPath xpath = XPathFactory.newInstance().newXPath();String expression = "/widgets/widget";InputSource inputSource = new InputSource("widgets.xml");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 coalescedinto one of the following other data types:

• Boolean

Final 1.0.0128

Package javax.xml.xpath

Page 139: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• Number

• String

The desired return type is specified by a javax.xml.namespace.QName parameter in method call used to evaluate theexpression, 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 thejavax.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, commentnode, 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:

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

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

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

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

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

Final 1.0.0129

Package javax.xml.xpath

Page 140: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XPathConstantsXPath constants.

Synopsispublic 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 ;

Final 1.0.0130

Package javax.xml.xpath

Page 141: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XPathFactoryAn 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.

Synopsispublic XPathFactory {

protected XPathFactory();

static XPathFactory newInstance();

static XPathFactory newInstance(java.lang.String uri)    throws XPathFactoryConfigurationException;

public boolean abstract isObjectModelSupported(java.lang.String objectModel);

Final 1.0.0131

Package javax.xml.xpath

Page 142: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 resolver);

public void abstract setXPathFunctionResolver(javax.xml.xpath.XPathFunctionResolver resolver);

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()] orjavax.xml.xpath.XPathFactory.newInstance [ Method newInstance(java.lang.String)] should be used to create a newinstance 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;

Final 1.0.0132

Package javax.xml.xpath

Page 143: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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. Anjavax.xml.xpath.XPathFactoryConfigurationException [ Exception XPathFactoryConfigurationException] is thrownif 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.

Final 1.0.0133

Package javax.xml.xpath

Page 144: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Method newInstance(String)

static XPathFactory newInstance(java.lang.String uri)    throws XPathFactoryConfigurationException;

Parameters

uri Identifies the underlying object model. The specification only defines the URIjavax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI [ Field DEFAULT_OB JECT_MODEL_URI], http://java.sun.com/jaxp/xpath/dom for the W3C DOM, theorg.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 classloader" 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 successfullycreated.

2. ${java.home}/lib/jaxp.properties is read and the value associated with the key being the system property aboveis looked for. If present, the value is processed just like above.

3. The class loader is asked for service provider provider-configuration files matchingjavax.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 defaultXPathFactory for the W3C DOM, i.e. javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI [ FieldDEFAULT_OBJECT_MODEL_URI].

If everything fails, an XPathFactoryConfigurationException will be thrown.

Tip for Trouble-shooting:

Final 1.0.0134

Package javax.xml.xpath

Page 145: JSR 206 Java API for XML Processing (JAXP) 1 · 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

See java.util.Properties.load for exactly how a property file is parsed. In particular, colons ':' need to be escaped in aproperty 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. Anjavax.xml.xpath.XPathFactoryConfigurationException [ Exception XPathFactoryConfigurationException] is thrownif 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 implementationmust not call the javax.xml.xpath.XPathFunctionResolver [ Interface XPathFunctionResolver] and must throw anjavax.xml.xpath.XPathFunctionException [ Exception XPathFunctionException].

Method setXPathFunctionResolver(XPathFunctionResolver)

public void abstract setXPathFunctionResolver(javax.xml.xpath.XPathFunctionResolver resolver);

Parameters

resolver XPath function resolver.

Final 1.0.0135

Package javax.xml.xpath

Page 146: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 resolver);

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 XPathXPath provides access to the XPath evaluation environment and expressions.

Evaluation of XPath Expressions.

If a request is made to evaluate the expression in the ab sence of a context item, an empty document node will be

context

used for the context. For the purposes of evaluating XPathexpressions, a DocumentFragment is treated like a Docu ment node.

If the expression contains a variable reference, its valuewill be found through the javax.xml.xpath.XPathVari 

variables

ableResolver [Interface XPathVariableResolver] set withjavax.xml.xpath.XPath.setXPathVariableResolver [MethodsetXPathVariableResolver(javax.xml.xpath.XPathVari ableResolver)]. An javax.xml.xpath.XPathExpressionEx ception [Exception XPathExpressionException] is raisedif the variable resolver is undefined or the resolver returnsnull for the variable. The value of a variable must beimmutable through the course of any single evaluation.

If the expression contains a function reference, the functionwill be found through the javax.xml.xpath.XPathFunction 

functions

Resolver [Interface XPathFunctionResolver] set withjavax.xml.xpath.XPath.setXPathFunctionResolver

Final 1.0.0136

Package javax.xml.xpath

Page 147: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Evaluation of XPath Expressions.

[Method setXPathFunct ionResolv  er(javax.xml.xpath.XPathFunctionResolver)]. Anjavax.xml.xpath.XPathExpressionException [ExceptionXPathExpressionException] is raised if the function resolv er is undefined or the function resolver returns null forthe function.

QNames in the expression are resolved against the XPathnamespace context set with javax.xml.xpath.XPath.set 

QNames

NamespaceContext [Method setNamespaceCon text(javax.xml.namespace.NamespaceContext)].

This result of evaluating an expression is converted to aninstance of the desired return type. Valid return types are

result

defined in javax.xml.xpath.XPathConstants [ClassXPathConstants]. Conversion to the return type followsXPath conversion rules.

Synopsisimplements 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;

Final 1.0.0137

Package javax.xml.xpath

Page 148: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 availablevia the javax.xml.xpath.XPathFunctionResolver [ Interface XPathFunctionResolver]. An javax.xml.xpath.XPathEx pressionException [ Exception XPathExpressionException] will be thrown if the XPathFunction cannot be resovledwith 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;

Final 1.0.0138

Package javax.xml.xpath

Page 149: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 aString.

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 QNameresolution 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 specifiedtype.

Final 1.0.0139

Package javax.xml.xpath

Page 150: JSR 206 Java API for XML Processing (JAXP) 1 · 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 method builds a data model for the org.xml.sax.InputSource and calls javax.xml.xpath.XPath.evaluate [ Methodevaluate(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 QNameresolution and return type conversion.

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants], then anIllegalArgumentException 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 aString.

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 QNameresolution 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.

Final 1.0.0140

Package javax.xml.xpath

Page 151: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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();

Final 1.0.0141

Package javax.xml.xpath

Page 152: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [ MethodnewXPath()]. reset() is designed to allow the reuse of existing XPaths thus saving resources associated with thecreation 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] orjavax.xml.namespace.NamespaceContext Objects, e.g. java.lang.Object.equals. It is guaranteed to have a functionallyequal 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.

Final 1.0.0142

Package javax.xml.xpath

Page 153: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Establish a variable resolver.

A NullPointerException is thrown if resolver is null.

Interface XPathExpressionXPathExpression provides access to compiled XPath expressions.

Evaluation of XPath Expressions.

If a request is made to evaluate the expression in the ab sence of a context item, an empty document node will be

context

used for the context. For the purposes of evaluating XPathexpressions, a DocumentFragment is treated like a Docu ment node.

If the expression contains a variable reference, its valuewill be found through the javax.xml.xpath.XPathVari 

variables

ableResolver [Interface XPathVariableResolver]. Anjavax.xml.xpath.XPathExpressionException [ExceptionXPathExpressionException] 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 throughthe course of any single evaluation.

If the expression contains a function reference, the functionwill be found through the javax.xml.xpath.XPathFunction 

functions

Resolver [Interface XPathFunctionResolver]. Anjavax.xml.xpath.XPathExpressionException [ExceptionXPathExpressionException] is raised if the function resolv er is undefined or the function resolver returns null forthe function.

QNames in the expression are resolved against the XPathnamespace context.

QNames

This result of evaluating an expression is converted to aninstance of the desired return type. Valid return types are

result

defined in javax.xml.xpath.XPathConstants [ClassXPathConstants]. Conversion to the return type followsXPath conversion rules.

Synopsisimplements 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;

Final 1.0.0143

Package javax.xml.xpath

Page 154: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 X M L P a t h L a n g u a g e ( X P a t h ) Ve r s i o n 1 . 0 , E x p r e s s i o n s[http://www.w3.org/TR/xpath#section-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 aString.

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, functionand 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;

Final 1.0.0144

Package javax.xml.xpath

Page 155: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thespecified 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, functionand QName resolution and return type conversion.

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants], then anIllegalArgumentException 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].

Final 1.0.0145

Package javax.xml.xpath

Page 156: JSR 206 Java API for XML Processing (JAXP) 1 · 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

See Evaluation of XPath Expressions [#XPathExpression-evaluation] for context item evaluation, variable, functionand 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, functionand QName resolution and return type conversion.

If returnType is not one of the types defined in javax.xml.xpath.XPathConstants [ Class XPathConstants], then anIllegalArgumentException 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 XPathFunctionXPathFunction provides access to XPath functions.

Functions are identified by QName and arity in XPath.

Synopsisimplements public XPathFunction {

public Object evaluate(java.util.List args)    throws XPathFunctionException;

Final 1.0.0146

Package javax.xml.xpath

Page 157: JSR 206 Java API for XML Processing (JAXP) 1 · 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

}

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 anyparticular number of times.

Interface XPathFunctionResolverXPathFunctionResolver 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 resolvercannot be used to override those functions.

In particular, the resolver is only called for functions in an another namespace (functions with an explicit prefix). Thismeans that you cannot use the XPathFunctionResolver to implement specifications like XML-Signature Syntaxand Processing [http://www.w3.org/TR/xmldsig-core/] which extend the function library of XPath 1.0 in the samenamespace. 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.

Synopsisimplements public XPathFunctionResolver {

Final 1.0.0147

Package javax.xml.xpath

Page 158: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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) Version 1.0, Core Function Library[http://www.w3.org/TR/xpath#corelib]

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 argumentsexists.

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 XPathVariableResolverXPathVariableResolver 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 enforcedby the API. Although variables may be mutable, that is, an application may wish to evaluate the same XPath expressionmore than once with different variable values, in the course of evaluating any single XPath expression, a variable'svalue must be immutable.

Synopsisimplements public XPathVariableResolver {

Final 1.0.0148

Package javax.xml.xpath

Page 159: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 valuereturned 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 XPathExceptionXPathException represents a generic XPath exception.

Synopsispublic 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);

Final 1.0.0149

Package javax.xml.xpath

Page 160: JSR 206 Java API for XML Processing (JAXP) 1 · 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

}

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.

Final 1.0.0150

Package javax.xml.xpath

Page 161: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exception XPathExpressionExceptionXPathExpressionException represents an error in an XPath expression.

Synopsispublic 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.

Final 1.0.0151

Package javax.xml.xpath

Page 162: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XPathFactoryConfigurationExceptionXPathFactoryConfigurationException represents a configuration error in a XPathFactory131 environment.

Synopsispublic 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

Final 1.0.0152

Package javax.xml.xpath

Page 163: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XPathFunctionExceptionXPathFunctionException represents an error with an XPath function.

Synopsispublic 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

Final 1.0.0153

Package javax.xml.xpath

Page 164: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0154

Package javax.xml.xpath

Page 165: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 14. Package javax.xml.validationThis package provides an API for validation of XML documents. Validation is the process of verifying that an XMLdocument is an instance of a specified XML schema. An XML schema defines the content model (also called agrammar 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 toconstrain 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 Organizationfor Standardization) [http://www.iso.org] standard.

• Schematron - a rules-based XML schema language. Whereas DTD, WXS, and RNG are designed to express thestructure of a content model, Schematron is designed to enforce individual rules that are difficult or impossible toexpress with other schema languages. Schematron is intended to supplement a schema written in structural schemalanguage 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 ajavax.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 providesa standard mechanism through which applications may take of advantage of specialization validation librarieswhich support additional schema languages.

• Easy runtime coupling of an XML instance and schema. Specifying the location of a schema to use for validationwith 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 (forreadability, some exception handling is not shown):

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

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

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

Final 1.0.0155

Page 166: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Schema schema = factory.newSchema(schemaFile);

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

// validate the DOM treetry {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.DocumentBuilderFactoryor 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 aschema and call setValidating(true) on a parser factory. The former technique will cause parsers to use thenew validation API; the latter will cause parsers to use their own internal validation facilities. Turning on both of theseoptions simultaneously will cause either redundant behavior or error conditions.

Class SchemaImmutable 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 acrossmany parsers in many threads.

A javax.xml.validation.Schema [ Class Schema] object is immutable in the sense that it shouldn't change the set ofconstraints once it is created. In other words, if an application validates the same document twice against the samejavax.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 isjavax.xml.validation.Validator [ Class Validator], which provides highly-level validation operations that cover typicaluse cases. The other is javax.xml.validation.ValidatorHandler [ Class ValidatorHandler], which works on top of SAXfor better modularity.

This specification does not refine the java.lang.Object.equals method. In other words, if you parse the same schematwice, you may still get !schemaA.equals(schemaB).

Synopsispublic Schema {

protected Schema();

public Validator abstract newValidator();

public ValidatorHandler abstract newValidatorHandler();

Final 1.0.0156

Package javax.xml.validation

Page 167: JSR 206 Java API for XML Processing (JAXP) 1 · 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

}

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 SchemaFactoryFactory that creates javax.xml.validation.Schema [ Class Schema] objects&#x2E; Entry-point to the validation API.

javax.xml.validation.SchemaFactory [ Class SchemaFactory] is a schema compiler. It reads external representationsof 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 [ ClassSchemaFactory] object at any given moment. Implementations are encouraged to mark methods as

Final 1.0.0157

Package javax.xml.validation

Page 168: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 fromthe same thread.

Schema LanguageThis spec uses a namespace URI to designate a schema language. The following table shows the values defined bythis specification.

To be compliant with the spec, the implementation is only required to support W3C XML Schema 1.0. However, if itchooses 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. Thejavax.xml.validation.SchemaFactory [ Class SchemaFactory] class is capable of locating other implementations forother 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 parsingprocess, it is impossible to define the DTD validation as a process independent from parsing. For this reason, thisspecification does not define the semantics for the XML DTD. This doesn't prohibit implentors from implementing itin a way they see fit, but users are warned that any DTD validation implemented on this interface necessarily deviatefrom the XML DTD semantics as defined in the XML 1.0.

languagevalue

W3C XML Schema 1.0[http://www.w3.org/TR/xmlschema-1]

j a v a x . x m l . X M L C o n  stants.W3C_XML_SCHEMA_NS_URI( " h t  tp://www.w3.org/2001/XMLS chema")

R E L A X N G 1 . 0[http://www.relaxng.org/]

j a v a x . x m l . X M L C o n s t a n t s . R E  LAXNG_NS_URI ("http://re l a x n g . o r g / n s / s t r u c  ture/1.0")

Synopsispublic 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;

Final 1.0.0158

Package javax.xml.validation

Page 169: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0159

Package javax.xml.validation

Page 170: JSR 206 Java API for XML Processing (JAXP) 1 · 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

The constructor does nothing.

Derived classes must create javax.xml.validation.SchemaFactory [ Class SchemaFactory] objects that have nullorg.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 thefeature 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.

Final 1.0.0160

Package javax.xml.validation

Page 171: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 atthis time.

NullPointerException if the name parameter is null.

See Also javax.xml.validation.SchemaFactory.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.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 propertynames.

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 avalid [#schemaLanguage] schema language.

Is specified schema supported by this SchemaFactory157?

Final 1.0.0161

Package javax.xml.validation

Page 172: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Method newInstance(String)

static SchemaFactory newInstance(java.lang.String schemaLanguage);

Parameters

schemaLanguage Specifies the schema language which the returned SchemaFactory will understand. Seethe 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 willtry 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 systemproperty 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 fileformat 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 defaultSchemaFactory157 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 aproperty file, so make sure schema language URIs are properly escaped in it. For example:

Final 1.0.0162

Package javax.xml.validation

Page 173: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 languagethat 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 thismethod.

W3C XML Schema 1.0

For XML Schema, this method creates a javax.xml.validation.Schema [ Class Schema] object that performs validationby using location hints specified in documents.

The returned javax.xml.validation.Schema [ Class Schema] object assumes that if documents refer to the same URLin 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 runfaster.

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.

Final 1.0.0163

Package javax.xml.validation

Page 174: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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, andjavax.xml.transform.dom.DOMSource.

returns Always return a non-null valid javax.xml.validation.Schema [ Class Schema] object. Note that whenan error has been reported, there is no guarantee that the returned javax.xml.validation.Schema [Class Schema] object is meaningful.

Final 1.0.0164

Package javax.xml.validation

Page 175: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 semanticsof 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 thehandler throws an exception, it will abort the schema compilation and the same exception will be thrown from thismethod. Also, after an error is reported to a handler, the callee is allowed to abort the further processing by throwingit. 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 thesesources were imported, using appropriate values for schemaLocation and namespace, into a single schema documentwith a different targetNamespace and no components of its own, if the import elements were given in the same orderas 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 behaviourbetween JAXP-compliant parsers may vary; in particular, parsers may choose to ignore all but the first <import> fora 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 errormust 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.

Final 1.0.0165

Package javax.xml.validation

Page 176: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thehandler. Or for example it can print an error to the screen and try to continue the processing by returning normallyfrom 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 callerof 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 withoutfirst 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.ErrorHandleris set:

class DraconianErrorHandler implementsorg.xml.sax.ErrorHandler {public void fatalError(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {throw e;}

Final 1.0.0166

Package javax.xml.validation

Page 177: JSR 206 Java API for XML Processing (JAXP) 1 · 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

public void error(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {throw e;}public void warning(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {// noop}}

When a new javax.xml.validation.SchemaFactory [ Class SchemaFactory] object is created, initially this field is setto 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 fromthis 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 thefeature 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 specificfeature 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:

Final 1.0.0167

Package javax.xml.validation

Page 178: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• true: the implementation will limit XML processing to conform to implementation limits. Examples include enityexpansion limits and XML Schema constructs that would consume large amounts of resources. If XML processingis 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 possibleimplementation 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 theproperty 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 propertynames.

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 needsto locate external resources while parsing schemas, although exactly what constitutes "locating external resources" isup to each schema language. For example, for W3C XML Schema, this includes files

<include>

Final 1.0.0168

Package javax.xml.validation

Page 179: JSR 206 Java API for XML Processing (JAXP) 1 · 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

d or

<import>

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 followingorg.w3c.dom.ls.LSResourceResolver is set:

class DumbDOMResourceResolver implementsorg.w3c.dom.ls.LSResourceResolver {publicorg.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 thenewSchema163 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 tojavax.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 TypeInfoProviderThis 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 eachattribute/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.

Synopsispublic TypeInfoProvider {

protected TypeInfoProvider();

public TypeInfo abstract getElementTypeInfo();

public TypeInfo abstract getAttributeTypeInfo(int index);

Final 1.0.0169

Package javax.xml.validation

Page 180: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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. Notethat the caller can keep references to the obtained org.w3c.dom.TypeInfo longer than the callbackscope. 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.

Final 1.0.0170

Package javax.xml.validation

Page 181: JSR 206 Java API for XML Processing (JAXP) 1 · 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

The method may only be called by the startElement event of the org.xml.sax.ContentHandler that the application setsto 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 setsto 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, thismeans 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 setsto the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler].

Final 1.0.0171

Package javax.xml.validation

Page 182: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

returnstrue

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 DOMtree 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 setsto 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 itwas added by the validator.

Class ValidatorA 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 makesure that one javax.xml.validation.Validator [ Class Validator] object is not used from more than one thread at anygiven time, and while the

Final 1.0.0172

Package javax.xml.validation

Page 183: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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)] andjavax.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.

Synopsispublic 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 $

Final 1.0.0173

Package javax.xml.validation

Page 184: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0174

Package javax.xml.validation

Page 185: JSR 206 Java API for XML Processing (JAXP) 1 · 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

org.xml.sax.SAXNotSup portedException

When the javax.xml.validation.Validator [ Class Validator] recognizes the feature namebut 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] torecognize a feature name but temporarily be unable to return its value. Some feature values may be available only inspecific 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 atthis 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] torecognize a property name but temporarily be unable to return its value. Some property values may be available onlyin 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].

Final 1.0.0175

Package javax.xml.validation

Page 186: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 resourcesassociated 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 rorHandlerObjects, 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.ErrorHandleris 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 theorg.xml.sax.ErrorHandler

If any java.lang.Throwable is thrown from an org.xml.sax.ErrorHandler, the caller of the validate method will bethrown 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.ErrorHandleris set:

class DraconianErrorHandler implementsorg.xml.sax.ErrorHandler {public void fatalError(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {throw e;}public void error(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {throw e;}

Final 1.0.0176

Package javax.xml.validation

Page 187: JSR 206 Java API for XML Processing (JAXP) 1 · 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

public void warning(org.xml.sax.SAXParseException e ) throwsorg.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 namebut 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, althoughjavax.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] toexpose a feature value but to be unable to change the current value. Some feature values may be immutable or mutableonly 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.

Final 1.0.0177

Package javax.xml.validation

Page 188: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 namebut 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] torecognize a property name but to be unable to change the current value. Some property values may be immutable ormutable 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 locateexternal resources while a validation, although exactly what constitutes "locating external resources" is up to eachschema language.

When the org.w3c.dom.ls.LSResourceResolver is null, the implementation will behave as if the followingorg.w3c.dom.ls.LSResourceResolver is set:

class DumbLSResourceResolver implementsorg.w3c.dom.ls.LSResourceResolver {publicorg.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 validatemethod 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.

Final 1.0.0178

Package javax.xml.validation

Page 189: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 canbe 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 tojavax.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.Sourcetype, or if the specified source is neither javax.xml.transform.sax.SAXSource norjavax.xml.transform.dom.DOMSource.

SAXException If the org.xml.sax.ErrorHandler throws a org.xml.sax.SAXException or if a fatal erroris found and the org.xml.sax.ErrorHandler returns normally.

IOException If the validator is processing a javax.xml.transform.sax.SAXSource and the underlyingorg.xml.sax.XMLReader throws an java.io.IOException.

NullPointerException If the

source

parameter is null.

Final 1.0.0179

Package javax.xml.validation

Page 190: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.Resultaccepted.

javax.xml.transform.Source/javax.xml.transform.Result accepted:

javax.xml.transform.dom.DOMSourcejavax.xml.transform.sax.SAXSource

OKOKnull

ErrOKjavax.xml.transform.sax.SAXResult

OKErrjavax.xml.transform.dom.DOMResult

Note that javax.xml.transform.stream.StreamSource instances are not allowed. To process a StreamSource113, orto 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 ValidatorHandlerStreaming validator that works on SAX stream.

A javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] object is a thread-unsafe, non-reentrant object. Inother words, it is the application's responsibility to make sure that one javax.xml.validation.ValidatorHandler [ ClassValidatorHandler] 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 constraintsdescribed in the associated javax.xml.validation.Schema [ Class Schema], and additionally it may modify the SAXevents (for example by adding default values, etc.)

javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] extends from org.xml.sax.ContentHandler, but itrefines 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 thoughSAX allows some of them to be null. Similarly, the user-specified org.xml.sax.ContentHandler will receive non-null Strings for all three parameters.

2. Applications must ensure that javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]'sorg.xml.sax.ContentHandler.startPrefixMapping and org.xml.sax.ContentHandler.endPrefixMapping are invokedproperly. Similarly, the user-specified org.xml.sax.ContentHandler will receive startPrefixMapping/endPrefixMap ping events. If the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] introduces additional namespacebindings, 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.

Final 1.0.0180

Package javax.xml.validation

Page 191: JSR 206 Java API for XML Processing (JAXP) 1 · 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

A javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] is automatically reset every time the startDocumentmethod is invoked.

Recognized Properties and FeaturesThis spec defines the following feature that must be recognized by all javax.xml.validation.ValidatorHandler [ ClassValidatorHandler] implementations.

http://xml.org/sax/features/namespace-prefixes

This feature controls how a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] introduces namespacebindings that were not present in the original SAX event stream. When this feature is set to true, it must make surethat the user's org.xml.sax.ContentHandler will see the corresponding xmlns* attribute in the org.xml.sax.Attributesobject of the org.xml.sax.ContentHandler.startElement callback. Otherwise, xmlns* attributes must not be added toorg.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 theorg.xml.sax.ContentHandler specified by the user.)

Note that this feature does NOT affect the way a javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] receivesSAX events. It merely changes the way it augments SAX events.

This feature is set to false by default.

Synopsispublic 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;

Final 1.0.0181

Package javax.xml.validation

Page 192: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [Method setContentHand ler(org.xml.sax.ContentHandler)]

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)]

Final 1.0.0182

Package javax.xml.validation

Page 193: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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] recognizesthe 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 beavailable 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 atthis time.

NullPointerException When the name parameter is null.

Final 1.0.0183

Package javax.xml.validation

Page 194: JSR 206 Java API for XML Processing (JAXP) 1 · 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

See Also javax.xml.validation.ValidatorHandler.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.ValidatorHandler [ Class Valid atorHandler] to recognize a property name but temporarily be unable to return its value. Some property values may beavailable 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 propertynames.

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 accessthe 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 exampleby adding defaulted attributes.

Final 1.0.0184

Package javax.xml.validation

Page 195: JSR 206 Java API for XML Processing (JAXP) 1 · 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

A javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may buffer events to certain extent, but to allowjavax.xml.validation.ValidatorHandler [ Class ValidatorHandler] to be used by a parser, the following requirementhas 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.ContentHandlermust be invoked for the same event before the callback returns.

2. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may not introduce new elements that were notpresent in the input.

3. javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] may not remove attributes that were present inthe input.

When a callback method on the specified org.xml.sax.ContentHandler throws an exception, the same exception objectmust be thrown from the javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]. The org.xml.sax.ErrorHandlershould 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.ErrorHandleris 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 theorg.xml.sax.ErrorHandler

If any java.lang.Throwable is thrown from an org.xml.sax.ErrorHandler, the same java.lang.Throwable object willbe thrown toward the root of the call stack.

javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] is not allowed to throw org.xml.sax.SAXExceptionwithout 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.ErrorHandleris set:

class DraconianErrorHandler implementsorg.xml.sax.ErrorHandler {public void fatalError(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {throw e;

Final 1.0.0185

Package javax.xml.validation

Page 196: JSR 206 Java API for XML Processing (JAXP) 1 · 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

}public void error(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {throw e;}public void warning(org.xml.sax.SAXParseException e ) throwsorg.xml.sax.SAXException {// noop}}

When a new javax.xml.validation.ValidatorHandler [ Class ValidatorHandler] object is created, initially this field isset 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] recognizesthe 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] parsesschemas, although javax.xml.validation.ValidatorHandler [ Class ValidatorHandler]s are not required to recognize anyspecific 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.

Final 1.0.0186

Package javax.xml.validation

Page 197: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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] recognizesthe 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 beimmutable 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 specificproperty 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 itneeds 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 followingorg.w3c.dom.ls.LSResourceResolver is set:

class DumbLSResourceResolver implementsorg.w3c.dom.ls.LSResourceResolver {publicorg.w3c.dom.ls.LSInput resolveResource(String publicId, String systemId, String baseURI) {

Final 1.0.0187

Package javax.xml.validation

Page 198: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thevalidate 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.

Final 1.0.0188

Package javax.xml.validation

Page 199: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 15. Package javax.xml.datatypeXML/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]

• X Q u e r y 1 . 0 a n d X P a t h 2 . 0 D a t a M o d e l , x d t : d a y T i m e D u r a t i o n[http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]

• X Q u e r y 1 . 0 a n d X P a t h 2 . 0 D a t a M o d e l , x d t : y e a r M o n t h D u r a t i o n[http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration]

Java Data TypeW3C XML Schema Data Type

javax.xml.datatype.XMLGregorianCal endar [Class XMLGregorianCalendar]

xs:date

javax.xml.datatype.XMLGregorianCal endar [Class XMLGregorianCalendar]

xs:dateTime

javax.xml.datatype.Duration [ClassDuration]

xs:duration

javax.xml.datatype.XMLGregorianCal endar [Class XMLGregorianCalendar]

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

Java Data TypeXQuery 1.0 and XPath 2.0 DataModel

javax.xml.datatype.Duration [ClassDuration]

xdt:dayTimeDuration

javax.xml.datatype.Duration [ClassDuration]

xdt:yearMonthDuration

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

• xs:anySimpleType

Final 1.0.0189

Page 200: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• 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 XPa th 2 .0 Da t a Mode l , xd t : dayTimeDura t i on[http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]

• See XQuery 1 .0 and XPath 2 .0 Data Model , xdt :yearMonthDurat ion[http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration]

• Since 1.5

Class DatatypeConstantsUtility class to contain basic Datatype values as constants.

Synopsisfinal DatatypeConstants {}

Author Jeff Suttor [mailto:[email protected]]

Version $Revision: 1.2.2.1 $, $Date: 2004/04/28 23:12:57 $

Final 1.0.0190

Package javax.xml.datatype

Page 201: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0191

Package javax.xml.datatype

Page 202: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0192

Package javax.xml.datatype

Page 203: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0193

Package javax.xml.datatype

Page 204: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0194

Package javax.xml.datatype

Page 205: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.FieldType-safe enum class that represents six fields of the javax.xml.datatype.Duration [ Class Duration] class.

Synopsisstatic 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 toend-users.

Class DatatypeFactoryFactory that creates new javax.xml.datatype Objects that map XML to/from Java Objects.

Final 1.0.0195

Package javax.xml.datatype

Page 206: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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, aclass with the name of the property's value is instantiated. Any Exception thrown during the instantiation processis 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 documentedin 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 processis wrapped as a javax.xml.datatype.DatatypeConfigurationException [ Exception DatatypeConfigurationException].

Synopsispublic 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);

Final 1.0.0196

Package javax.xml.datatype

Page 207: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 lexicalRepresentation);

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.util.GregorianCalendar cal);

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.math.BigInteger year,                                                               int month,                                                               int day,                                                               int hour,                                                               int minute,                                                               int second,                                                               java.math.BigDecimal fractionalSecond,                                                               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,

Final 1.0.0197

Package javax.xml.datatype

Page 208: JSR 206 Java API for XML Processing (JAXP) 1 · 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

                                                          int seconds,                                                          int timezone);

public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                          int minutes,                                                          int seconds,                                                          java.math.BigDecimal fractionalSecond,                                                          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.

Final 1.0.0198

Package javax.xml.datatype

Page 209: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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, thisparameter 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 beincapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will bethrown 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,

Final 1.0.0199

Package javax.xml.datatype

Page 210: JSR 206 Java API for XML Processing (JAXP) 1 · 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

                              int minutes,                              int seconds);

Parameters

isPositive Set to false to create a negative duration. When the length of the duration is zero, thisparameter 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.

See Also 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 thatfield 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 wherethe coordinates designate the Gregorian year, month, day, hour, minute, and second componentsdefined 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.

Final 1.0.0200

Package javax.xml.datatype

Page 211: JSR 206 Java API for XML Processing (JAXP) 1 · 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

All six values are set by computing their values from the specified milliseconds and are availabe using the get methodsof 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 D, ISO 8601 Date and Time Formats[http://www.w3.org/TR/xmlschema-2/#isoformats]

• javax.xml.datatype.XMLGregorianCalendar [ Class XMLGregorianCalendar] Date/Time Datatype Field MappingBetween 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.getMonths [ Method getMonths()] andjavax.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 wherethe coordinates designate the Gregorian year, month, day, hour, minute, and second componentsdefined 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 beincapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will bethrown with a message indicating implementation limits if implementation capacities are exceeded.

Final 1.0.0201

Package javax.xml.datatype

Page 212: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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, thisparameter 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 secondas 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 onlyday, 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 beincapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will bethrown 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);

Final 1.0.0202

Package javax.xml.datatype

Page 213: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Parameters

isPositive Set to false to create a negative duration. When the length of the duration is zero, thisparameter 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 secondas 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 onlyday, 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 thatfield 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, xdt:dayTimeDuration[http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration]

Create a Duration213 of type xdt:dayTimeDuration using the specified milliseconds as defined in XQuery1.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 onlyday, 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 getmethods 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

Final 1.0.0203

Package javax.xml.datatype

Page 214: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• W3C XML Schema 1.0 Part 2, Appendix D, ISO 8601 Date and Time Formats[http://www.w3.org/TR/xmlschema-2/#isoformats]

• javax.xml.datatype.XMLGregorianCalendar [ Class XMLGregorianCalendar] Date/Time Datatype Field MappingBetween 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",X Q u e r y 1 . 0 a n d X P a t h 2 . 0 D a t a M o d e l , x d t : d a y T i m e D u r a t i o n[http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration].

The datatype xdt:dayTimeDuration is a subtype of xs:duration whose lexical representation contains onlyday, 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 beincapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will bethrown 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);

Final 1.0.0204

Package javax.xml.datatype

Page 215: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Parameters

isPositive Set to false to create a negative duration. When the length of the duration is zero, thisparameter 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 inX Q u e r y 1 . 0 a n d X P a t h 2 . 0 D a t a M o d e l , x d t : y e a r M o n t h D u r a t i o n[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 beincapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will bethrown 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, thisparameter 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 inX Q u e r y 1 . 0 a n d X P a t h 2 . 0 D a t a M o d e l , x d t : y e a r M o n t h D u r a t i o n[http://www.w3.org/TR/xpath-datamodel#dt-yearMonthyDuration].

Final 1.0.0205

Package javax.xml.datatype

Page 216: JSR 206 Java API for XML Processing (JAXP) 1 · 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

A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates thatfield 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 XQuery1.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 containsonly 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 methodsof 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 D, ISO 8601 Date and Time Formats[http://www.w3.org/TR/xmlschema-2/#isoformats]

• javax.xml.datatype.XMLGregorianCalendar [ Class XMLGregorianCalendar] Date/Time Datatype Field MappingBetween 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.getMonths [ Method getMonths()] can beinfluenced.

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.

Final 1.0.0206

Package javax.xml.datatype

Page 217: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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",X Q u e r y 1 . 0 a n d X P a t h 2 . 0 D a t a M o d e l , x d t : y e a r M o n t h D u r a t i o n[http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration].

The datatype xdt:yearMonthDuration is a subtype of xs:duration whose lexical representation containsonly 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 beincapable of supporting arbitrarily large and/or small values. An java.lang.UnsupportedOperationException will bethrown 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 fractionalSecond,                                                               int timezone);

Final 1.0.0207

Package javax.xml.datatype

Page 218: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 fieldas determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute aninvalid 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:dateTimeand related builtin datatypes. Note that year parameter supports arbitrarily large numbers and fractionalSecond hasinfinite precision.

A null value indicates that field isnot set.

Method newXMLGregorianCalendar(GregorianCalendar)

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.util.GregorianCalendar cal);

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.

Final 1.0.0208

Package javax.xml.datatype

Page 219: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Field by Field Conversion from java.util.GregorianCalendar to anjavax.xml.datatype.XMLGregorianCalendar [Class XMLGregorianCalendar]

javax.xml.datatype.XML GregorianCalendar field

java.util.GregorianCalen dar field

javax.xml.datatype.XMLGregorianCal endar.setYear [Method setYear(int)]

ERA == GregorianCalen dar.BC ? -YEAR : YEAR

javax.xml.datatype.XMLGregorianCal endar.setMonth [Method set Month(int)]

MONTH + 1

javax.xml.datatype.XMLGregorianCal endar.setDay [Method setDay(int)]

DAY_OF_MONTH

javax.xml.datatype.XMLGregorianCal endar.setTime [Method setTime(int,int, int, java.math.BigDecimal)]

HOUR_OF_DAY, MINUTE,SECOND, MILLISECOND

javax.xml.datatype.XMLGregorianCal endar.setTimezone [Method set 

Timezone(int)]*

(ZONE_OFFSET + DST_OFFSET)/ (60*1000)(in minutes)

*conversion loss of information. It is not possible to represent a java.util.GregorianCalendar daylightsavings 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 customtimezone id using the this.getTimezone().

• else use the GregorianCalendar default timezone value for the host is defined as specified byjava.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.

Final 1.0.0209

Package javax.xml.datatype

Page 220: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 fieldas determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute aninvalid 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 thatfield isnot set.

Method newXMLGregorianCalendar(String)

public XMLGregorianCalendar abstract newXMLGregorianCalendar(java.lang.String lexicalRepresentation);

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)

Final 1.0.0210

Package javax.xml.datatype

Page 221: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [ FieldFIELD_UNDEFINED] indicates optional field is not set.

returns XMLGregorianCalendar227 created from parameter values.

Exceptions

IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the fieldas determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute aninvalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM LGregorianCalendar.isValid [ Method isValid()].

See Also 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 tojavax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED].

A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates thatfield isnot set.

Method newXMLGregorianCalendarTime(int, int, int, BigDecimal, int)

public XMLGregorianCalendar newXMLGregorianCalendarTime(int hours,                                                          int minutes,                                                          int seconds,                                                          java.math.BigDecimal fractionalSecond,                                                          int timezone);

Parameters

hours number of hours

minutes number of minutes

Final 1.0.0211

Package javax.xml.datatype

Page 222: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [ FieldFIELD_UNDEFINED] indicates optional field is not set.

returns XMLGregorianCalendar227 created from parameter values.

Exceptions

IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the fieldas determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute aninvalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM LGregorianCalendar.isValid [ Method isValid()].

See Also 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 thatfield 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 [ FieldFIELD_UNDEFINED] indicates optional field is not set.

returns XMLGregorianCalendar227 created from parameter values.

Exceptions

IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the fieldas determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute aninvalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM LGregorianCalendar.isValid [ Method isValid()].

See Also javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [Field FIELD_UNDEFINED]

Final 1.0.0212

Package javax.xml.datatype

Page 223: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Create a Java instance of XML Schema builtin datatype time.

A javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED] value indicates thatfield 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 [ FieldFIELD_UNDEFINED] indicates optional field is not set.

returns XMLGregorianCalendar227 created from parameter values.

Exceptions

IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the fieldas determined by the Date/Time Data Mapping table in javax.xml.datatype.XMLGregori anCalendar [ Class XMLGregorianCalendar] or if the composite values constitute aninvalid XMLGregorianCalendar227 instance as determined by javax.xml.datatype.XM LGregorianCalendar.isValid [ Method isValid()].

See Also 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 thatfield isnot set.

Class DurationImmutable 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 secondsfield has a non-negative decimal or null. A negative sign indicates a negative duration.

Final 1.0.0213

Package javax.xml.datatype

Page 224: JSR 206 Java API for XML Processing (JAXP) 1 · 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 class provides a number of methods that make it easy to use for the duration datatype of XML Schema 1.0 withthe errata.

Order relationshipDuration objects only have partial order, where two values A and B maybe either:

1. A<B (A is shorter than B)

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 fordetails 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 cannotsubtract 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 finiteprecision 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 [ ClassDuration] 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.

Synopsispublic Duration {

public Duration();

public QName getXMLSchemaType();

public int abstract getSign();

public int getYears();

public int getMonths();

Final 1.0.0214

Package javax.xml.datatype

Page 225: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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

Final 1.0.0215

Package javax.xml.datatype

Page 226: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 dayto 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 injava.lang.IllegalStateException. Formally, the computation is defined as follows. Firstly, we can assume that twoDuration213s 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 missingfields are treated as 0. A field of the resulting Duration213 will be unset if and only if respective fields of two inputDuration213s are unset. Note that lhs.add(rhs) will be always successful iflhs.signum()*rhs.signum()!=-1 or both of them are normalized.

Method addTo(Calendar)

public void abstract addTo(java.util.Calendar calendar);

Final 1.0.0216

Package javax.xml.datatype

Page 227: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 caseswhere 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.Calendarobject is based on some other calendar systems.

Any fractional parts of this Duration213 object beyond milliseconds will be simply ignored. For example, if thisduration 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 avoidingthe 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 thejavax.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.Dateobject.

This somewhat redundant computation is necessary to unambiguously determine the duration of months and years.

Final 1.0.0217

Package javax.xml.datatype

Page 228: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Method compare(Duration)

public int abstract compare(javax.xml.datatype.Duration duration);

Parameters

duration to compare

returns the relationship between thisDuration213and duration parameter as javax.xml.datatype.Data typeConstants.LESSER [ Field LESSER], javax.xml.datatype.DatatypeConstants.EQUAL [ FieldEQUAL], javax.xml.datatype.DatatypeConstants.GREATER [ Field GREATER] orjavax.xml.datatype.DatatypeConstants.INDETERMINATE [ Field INDETERMINATE].

Exceptions

UnsupportedOperationEx ception

If the underlying implementation cannot reasonably process the request, e.g. W3C XMLSchema allows for arbitrarily large/small/precise values, the request may be beyond theimplementations 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 onduration [http://www.w3.org/TR/xmlschema-2/#duration-order].

Return:

• javax.xml.datatype.DatatypeConstants.LESSER [ Field LESSER] if this Duration213 is shorter than durationparameter

• javax.xml.datatype.DatatypeConstants.EQUAL [ Field EQUAL] if this Duration213 is equal to durationparameter

• javax.xml.datatype.DatatypeConstants.GREATER [ Field GREATER] if this Duration213 is longer than durationparameter

• javax.xml.datatype.DatatypeConstants.INDETERMINATE [ Field INDETERMINATE] if a conclusive partialorder 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.

Final 1.0.0218

Package javax.xml.datatype

Page 229: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

UnsupportedOperationEx ception

If the underlying implementation cannot reasonably process the request, e.g. W3C XMLSchema allows for arbitrarily large/small/precise values, the request may be beyond theimplementations 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 inthe 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. Forexample,

!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 likejavax.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 objectthat 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 returnsa 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 designedto return a java.lang.Number object. In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returnednumber will be a non-negative integer. In case of seconds, the returned number may be a non-negative decimal value.

Final 1.0.0219

Package javax.xml.datatype

Page 230: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 likejavax.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 likejavax.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 likejavax.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 likejavax.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 thisvariance. Specifically, this method returns the difference between startInstant andstartInstant+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,

Final 1.0.0220

Package javax.xml.datatype

Page 231: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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, whichmay 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 thisvariance. Specifically, this method returns the difference between startInstant andstartInstant+duration.

returns milliseconds between startInstant and startInstant plus this Duration213

Exceptions

NullPointerException If the startInstant parameter is null.

See Also 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, whichmay 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();

Final 1.0.0221

Package javax.xml.datatype

Page 232: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 thatare 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)

secondminutehourdaymonthyearDatatype

XXXXXXjavax.xml.data t y p e . D a t a  t y p e C o n  stants.DURA TION [FieldDURATION]

XXXXjavax.xml.data t y p e . D a t a  t y p e C o n  stants.DURA T I O N _ DAY  TIME [FieldD U R A  TION_DAY  TIME]

XXjavax.xml.data t y p e . D a t a  t y p e C o n  stants.DURA TION_YEAR MONTH [FieldD U R A  TION_YEAR MONTH]

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 therange 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();

Final 1.0.0222

Package javax.xml.datatype

Page 233: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XMLSchema allows for arbitrarily large/small/precise values, the request may be beyond theimplementations 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 afield is present.

Method isShorterThan(Duration)

public boolean isShorterThan(javax.xml.datatype.Duration duration);

Final 1.0.0223

Package javax.xml.datatype

Page 234: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 XMLSchema allows for arbitrarily large/small/precise values, the request may be beyond theimplementations 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 anew Duration object and returns it. The operation will be performed field by field with the precision ofjava.math.BigDecimal. Since all the fields except seconds are restricted to hold integers, any fraction produced by thecomputation 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. Forexample 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.

Final 1.0.0224

Package javax.xml.datatype

Page 235: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 anew 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.addmethod

Final 1.0.0225

Package javax.xml.datatype

Page 236: JSR 206 Java API for XML Processing (JAXP) 1 · 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

3. the difference between the two Calendars in computed in milliseconds and converted to days, if a remainder occursdue 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 constructa new Duration object.

Note that since the Calendar class uses int to hold the value of year and month, this method may produce an unexpectedresult 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 dayfrom 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 injava.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)=-(X-Y))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

Final 1.0.0226

Package javax.xml.datatype

Page 237: JSR 206 Java API for XML Processing (JAXP) 1 · 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

F

.This process is repeated until all the non-zero fields have the same sign.If a borrow occurs in the days field (in otherwords, if the computation needs to borrow 1 or -1 month to compensate days), then the computation fails by throwingan 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 equivalentDuration213Object 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 XMLGregorianCalendarRepresentation 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 Schema1.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 alsosummarizes 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

Value RangeRelatedXMLGregorianCalen darAccessor(s)

XML Schema 1.0 datatypefield

getYear() is a valuebetween -(10^9-1) to (10^9)-

javax.xml.datatype.XML GregorianCalendar.getYear[Method getYear()] +

year

1 or javax.xml.datatype.Data javax.xml.datatype.XML  typeConstants.FIELD_UN GregorianCalendar.getEon DEFINED [Fie ld[Method getEon()] or  F I E L D _ U N  javax.xml.datatype.XML  DEFINED].javax.xml.data G r e g o r i a n C a l e n   type.XMLGregorianCalen dar.getEonAndYear [MethodgetEonAndYear()]

dar.getEon [MethodgetEon()] is high order yearvalue in billion ofyears.getEon() has valuesgreater than or equal to(10^9) or less than or equal

Final 1.0.0227

Package javax.xml.datatype

Page 238: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation

to -(10^9). A value of nullindicates field is undefined.Given that XML Schema 1.0e r r a t a[http://www.w3.org/2001/05/xmlschema-errata#e2-63]states that the year zero willbe a valid lexical value in afuture version of XMLSchema, this class allows theyear field to be set to zero.Otherwise, the year fieldvalue is handled exactly asdescribed in the errata and[ISO-8601-1988]. Note thatW3C XML Schema 1.0 val idation does not allow for theyear field to have a value ofzero.

1 to 12 or javax.xml.data t y p e . D a t a t y p e C o n  

javax.xml.datatype.XML GregorianCalendar.getMonth[Method getMonth()]

month

stants.FIELD_UNDEFINED[Field FIELD_UN DEFINED]

Independent of month, maxrange is 1 to 31 or

javax.xml.datatype.XML GregorianCalendar.getDay[Method getDay()]

day

javax.xml.datatype.Data typeConstants.FIELD_UN DEFINED [Fie ldFIELD_UNDEFINED]. Thenormative value constraintstated relative to monthfield's value is in W3C XMLSchema 1.0 Part 2, AppendixD[http://www.w3.org/TR/xmlschema-2/#isoformats].

0 to 24 or javax.xml.data t y p e . D a t a t y p e C o n  

javax.xml.datatype.XML GregorianCalendar.getHour[Method getHour()]

hour

stants.FIELD_UNDEFINED[Field FIELD_UN DEFINED]. For a value of24, the minute and secondfield must be zero per XMLS c h e m a E r r a t a[http://www.w3.org/2001/05/xmlschema-errata#e2-45].

0 to 59 or javax.xml.data t y p e . D a t a t y p e C o n  

javax.xml.datatype.XML GregorianCalendar.get  

minute

stants.FIELD_UNDEFINEDMinute [Method get Minute()] [Field FIELD_UN 

DEFINED]

Final 1.0.0228

Package javax.xml.datatype

Page 239: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation

javax.xml.datatype.XML GregorianCalendar.get  

javax.xml.datatype.XML GregorianCalendar.get  

second

Second [Method get Second [Method get Second()] from 0 to 60 orSecond()] + javax.xml.data javax.xml.datatype.Data type.XMLGregorianCalen typeConstants.FIELD_UN dar.getMillisecond [MethodDEFINED [Fie ldgetMillisecond()]/1000 or F I E L D _ U N  javax.xml.datatype.XML DEFINED].(Note: 60 onlyGregorianCalendar.get  allowable for leapSecond [Method get second.)javax.xml.data  Second()] + javax.xml.data type.XMLGregorianCalen type.XMLGregorianCalen dar.getFractionalSeconddar.getFractionalSecond[Method getFraction [Method getFraction 

alSecond()] alSecond()] allows for infin ite precision over the rangefrom 0.0 to 1.0 when thejavax.xml.datatype.XML GregorianCalendar.get  Second [Method get Second()] is defined.Frac tionalSecond is optionaland has a value of nullw h e n i t i s u n  defined.javax.xml.data  type.XMLGregorianCalen dar.getMillisecond [MethodgetMillisecond()] is the con venience millisecond preci s i o n o f va l u e o fjavax.xml.datatype.XML GregorianCalendar.getFrac tionalSecond [Method get FractionalSecond()].

Number of minutes orjavax.xml.datatype.Data 

javax.xml.datatype.XML GregorianCalendar.get  

timezone

typeConstants.FIELD_UN Timezone [Method get Timezone()] DEFINED [Fie ld

FIELD_UNDEFINED].Value range from -14 hours(-14 * 60 minutes) to 14hours (14 * 60 minutes).

All maximum value space constraints listed for the fields in the table above are checked by factory methods, @{linkDatatypeFactory}, setter methods and parse methods of this class. IllegalArgumentException is thrown whena 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 forthis class:

• accessors/mutators for independent date/time fields

Final 1.0.0229

Package javax.xml.datatype

Page 240: JSR 206 Java API for XML Processing (JAXP) 1 · 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

• 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 tojavax.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 Schema1 . 0 P a r t 2 , A p p e n d i x E , A d d i n g d u r a t i o n s t o d a t e T i m e s[http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes].

Synopsispublic 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,

Final 1.0.0230

Package javax.xml.datatype

Page 241: JSR 206 Java API for XML Processing (JAXP) 1 · 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

                      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.XMLGregorianCalendar defaults);

public TimeZone abstract getTimeZone(int defaultZoneoffset);

public Object abstract clone();

Final 1.0.0231

Package javax.xml.datatype

Page 242: JSR 206 Java API for XML Processing (JAXP) 1 · 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

}

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' representationof 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] andreference fields to null.

Method clone()

public Object abstract clone();

Creates and returns a copy of this object.

Final 1.0.0232

Package javax.xml.datatype

Page 243: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Method compare(XMLGregorianCalendar)

public int abstract compare(javax.xml.datatype.XMLGregorianCalendar xmlGregorianCalendar);

Parameters

xmlGregorianCalendar Instance of XMLGregorianCalendar227 to compare

returns The relationship between thisXMLGregorianCalendar227 and the specified xml 

GregorianCalendar as javax.xml.datatype.DatatypeConstants.LESSER [ FieldLESSER], javax.xml.datatype.DatatypeConstants.EQUAL [ Field EQUAL],javax.xml.datatype.DatatypeConstants.GREATER [ Field GREATER] orjavax.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 inW3C 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)] returnsjavax.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].

Final 1.0.0233

Package javax.xml.datatype

Page 244: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 ofthe 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]. Returnsjavax.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();

Final 1.0.0234

Package javax.xml.datatype

Page 245: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 byjavax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFractionalSecond()]. The returned valueis the rounded down to milliseconds value of javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [Method getFractionalSecond()]. When javax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ MethodgetFractionalSecond()] 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 isnot 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 isnot defined. When this field is not defined, the optional xs:dateTime fractional seconds field, represented byjavax.xml.datatype.XMLGregorianCalendar.getFractionalSecond [ Method getFractionalSecond()] andjavax.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].

Final 1.0.0235

Package javax.xml.datatype

Page 246: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [ FieldFIELD_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. Iftimezone 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 Schemabuiltin date/time datatypes.

Return the name of the XML Schema date/time type that this instance maps to. Type is computed based on fields thatare set.

Required fields for XML Schema 1.0 Date/Time Datatypes.(timezone is optional for all date/time datatypes)

secondminutehourdaymonthyearDatatype

XXXXXXjavax.xml.data t y p e . D a t a  t y p e C o n  stants.DATE  TIME [FieldDATETIME]

XXXjavax.xml.data t y p e . D a t a  t y p e C o n  

Final 1.0.0236

Package javax.xml.datatype

Page 247: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Required fields for XML Schema 1.0 Date/Time Datatypes.(timezone is optional for all date/time datatypes)

s tan ts .DATE[Field DATE]

XXXjavax.xml.data t y p e . D a t a  t y p e C o n  s t an t s .T IME[Field TIME]

XXjavax.xml.data t y p e . D a t a  t y p e C o n  stants.GYEAR MONTH [FieldG Y E A R  MONTH]

XXjavax.xml.data t y p e . D a t a  t y p e C o n  stants.GMONTHDAY[ F i e l dGMONTHDAY]

Xjavax.xml.data t y p e . D a t a  t y p e C o n  stants.GYEAR[Field GYEAR]

Xjavax.xml.data t y p e . D a t a  t y p e C o n  stants.GMONTH[ F i e l dGMONTH]

Xjavax.xml.data t y p e . D a t a  t y p e C o n  stants.GDAY[Field GDAY]

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].

Final 1.0.0237

Package javax.xml.datatype

Page 248: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 [ MethodnewXMLGregorianCalendarTime(int, int, int, int, int)].

reset() is designed to allow the reuse of existing XMLGregorianCalendar227s thus saving resources associatedwith 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].

Final 1.0.0238

Package javax.xml.datatype

Page 249: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

IllegalArgumentException if day parameter is outside value constraints for the field as specified in date/time fieldmapping 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 indate/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 fieldmapping 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].

Final 1.0.0239

Package javax.xml.datatype

Page 250: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

IllegalArgumentException if millisecond parameter is outside value constraints for the field as specified indate/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/timefield 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/timefield 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].

Final 1.0.0240

Package javax.xml.datatype

Page 251: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

IllegalArgumentException if second parameter is outside value constraints for the field as specified in date/timefield 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 if any parameter is outside value constraints for the field as specified in date/time fieldmapping table [#datetimefieldmapping].

See Also javax.xml.datatype.XMLGregorianCalendar.setTime [Method setTime(int, int, int,java.math.BigDecimal)]

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.

Final 1.0.0241

Package javax.xml.datatype

Page 252: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

IllegalArgumentException if any parameter is outside value constraints for the field as specified in date/time fieldmapping 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 [ FieldFIELD_UNDEFINED] indicates this optional field is not set.

Exceptions

IllegalArgumentException if any parameter is outside value constraints for the field as specified in date/time fieldmapping table [#datetimefieldmapping].

Set time as one unit, including optional milliseconds.

Method setTimezone(int)

public void abstract setTimezone(int offset);

Parameters

offset value constraints summarized in timezone field of date/time field mapping table[#datetimefield-timezone].

Exceptions

IllegalArgumentException if offset parameter is outside value constraints for the field as specified in date/timefield 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].

Final 1.0.0242

Package javax.xml.datatype

Page 253: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 fieldmapping 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 yearis javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED [ Field FIELD_UNDEFINED], then eon isset 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 tonull 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.GregorianCalendardefault for its corresponding field. A notable difference between XML Schema 1.0 date/time datatypes andjava.util.GregorianCalendar is that Timezone value is optional for date/time datatypes and it is a requiredfield for java.util.GregorianCalendar. See javadoc for java.util.TimeZone.getDefault() onhow 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)].

Final 1.0.0243

Package javax.xml.datatype

Page 254: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Field by Field Conversion from this class to java.util.GregorianCalendar

javax.xml.datatype.XMLGregorianCalendarfield

java.util.GregorianCalendar field

javax.xml.datatype.XMLGregorianCalendar.getEonAn dYear [Method getEonAndYear()].signum() < 0 ?

ERA

GregorianCalendar.BC : GregorianCalen dar.AD

javax.xml.datatype.XMLGregorianCalendar.getEonAn dYear [Method getEonAndYear()].abs().int Value()*

YEAR

javax.xml.datatype.XMLGregorianCalendar.getMonth[Method getMonth()] - javax.xml.datatype.DatatypeCon 

MONTH

stants.JANUARY [Field JANUARY] + java.util.Calen dar.JANUARY

javax.xml.datatype.XMLGregorianCalendar.getDay[Method getDay()]

DAY_OF_MONTH

javax.xml.datatype.XMLGregorianCalendar.getHour[Method getHour()]

HOUR_OF_DAY

javax.xml.datatype.XMLGregorianCalendar.getMinute[Method getMinute()]

MINUTE

javax.xml.datatype.XMLGregorianCalendar.getSecond[Method getSecond()]

SECOND

get millisecond order from javax.xml.datatype.XML GregorianCalendar.getFractionalSecond [Method getFrac tionalSecond()]*

MILLISECOND

javax.xml.datatype.XMLGregorianCalendar.getTimezone[Method getTimezone()] formatted into Custom timezoneid

GregorianCalendar.setTimeZone(TimeZone)

* designates possible loss of precision during the conversion due to source datatype having higher precision than targetdatatype. To ensure consistency in conversion implementations, the new GregorianCalendar should be instantiatedin 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( newDate(Long.MIN_VALUE)).

• Its fields ERA, YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, SECOND and MILLISECONDare 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.XMLGregorianCalendar defaults);

Final 1.0.0244

Package javax.xml.datatype

Page 255: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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, thisconversion 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 acustom timezone id using the this.getTimezone().

• else when defaults.getTimezone() != FIELD_UNDEFINED, create a java.util.TimeZone witha custom timezone id using defaults.getTimezone().

• else use the GregorianCalendar default timezone value for the host is defined as specified byjava.util.TimeZone.getDefault().

Method toString()

public String toString();

Exceptions

IllegalStateException if the combination of set fields does not match one of the eight defined XML Schemabuiltin date/time datatypes.

See Also 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();

Final 1.0.0245

Package javax.xml.datatype

Page 256: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Exceptions

IllegalStateException if the combination of set fields does not match one of the eight defined XML Schemabuiltin date/time datatypes.

Return the lexical representation of this instance. The format is specified in XML Schema 1.0 Part 2, Section 3.2.[7-14].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 DatatypeConfigurationExceptionIndicates a serious configuration error.

TODO: support all constructors

Synopsispublic 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

Final 1.0.0246

Package javax.xml.datatype

Page 257: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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.

Final 1.0.0247

Package javax.xml.datatype

Page 258: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 16. Package javax.xmlDefines 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 XMLConstantsUtility class to contain basic XML values as constants.

Synopsisfinal 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 MarkupLanguage (XML) 1.0 (Second Edition) [http://www.w3.org/TR/REC-xml], XML 1.0 SecondEdition Specification Errata [http://www.w3.org/XML/xml-V10-2e-errata], Namespaces in XML1.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 ;

Final 1.0.0248

Page 259: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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 avoidconditions such as denial of service attacks.

• false instructs the implementation to process XML acording the letter of the XML specifications ingoring securityissues 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 N a m e s p a c e s i n X M L , 5 . 2 N a m e s p a c e D e f a u l t i n g[http://www.w3.org/TR/REC-xml-names/#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 ;

Final 1.0.0249

Package javax.xml

Page 260: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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/REC-xml".

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".

Final 1.0.0250

Package javax.xml

Page 261: JSR 206 Java API for XML Processing (JAXP) 1 · 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

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/".

Final 1.0.0251

Package javax.xml

Page 262: JSR 206 Java API for XML Processing (JAXP) 1 · 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

Chapter 17. ColophonTalk 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. TheXSL Formatting Objects were then transformed into PDF.

Table 17.1. XML Usage Conventions

"external-spec" is the type of all ulinks that refer to externalspecifications

<ulink type="external-spec">

"organization" is the type of all ulinks that refer to organ izations

<ulink type="organization">

Final 1.0.0252