Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 42 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
42
Dung lượng
1,23 MB
Nội dung
188 Essential XML Quick Reference Java public void processEmployeeDocument() { // instantiate Xerces-J SAX parser XMLReader reader = new org.apache.xerces.parsers.SAXParser(); // EmployeeHandler implements ContentHandler, // ErrorHandler, DTDHandler, and EntityResolver ContentHandler handler = new EmployeeHandler(); // register handlers with XMLReader reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.setDTDHandler(handler); reader.setEntityResolver(handler); try { // register LexicalHandler implementation reader.setProperty( "http://xml.org/sax/properties/lexical-handler", handler); reader.setFeature( "http://xml.org/sax/features/namespaces", true); reader.setFeature( "http://xml.org/sax/features/namespace- prefixes", true); // start parsing reader.parse("file://c:\temp\employee.xml"); } catch(Exception e) { // handle errors here } } Skonnard.book Page 188 Monday, October 1, 2001 8:57 AM SAX 2.0 189 SAX VB Public Sub processEmployeeDocument() On Error Goto HandleError ' instantiate MSXML 3.0 SAX parser Dim reader as New SAXXMLReader ' EmployeeHandler implements ContentHandler, ' ErrorHandler, DTDHandler, & EntityResolver Dim handler as New EmployeeHandler ' register handlers with XMLReader set reader.contentHandler = handler set reader.errorHandler = handler set reader.dtdHandler = handler set reader.entityResolver = handler ' register LexicalHandler implementation reader.putProperty _ "http://xml.org/sax/properties/lexical-handler",_ handler reader.putFeature _ "http://xml.org/sax/features/namespaces",_ true reader.putFeature _ "http://xml.org/sax/features/namespace-prefixes",_ true reader.parseURL "file://c:\temp\employee.xml" Exit Sub HandleError: ' handle errors here End Sub Skonnard.book Page 189 Monday, October 1, 2001 8:57 AM 190 Essential XML Quick Reference 6.3 Features and properties XMLReader has four configuration methods: two that deal with properties and two that deal with features. Properties are uniquely named values that can be associated with an XMLReader instance. Features can be viewed as configuration-specific boolean properties that are used to turn specific processing features on or off. SAX predefines a set of well-known properties and features. These properties and features are as follows. SAX implementations may add custom features and prop- erties that have implementation-specific URI-based names. Features The full feature name should be prefixed with http://xml.org/sax/fea- tures/ (for example, http://xml.org/sax/features/namespaces). Properties The full property name should be prefixed with http://xml.org/sax/prop- erties/ (for example, http://xml.org/sax/properties/dom-node). Name Description namespaces Performs namespace processing. namespace-prefixes Reports the original prefixed names and attributes used for namespace declarations. string-interning Internalizes all element names, prefixes, attribute names, namespace identifiers, and local names using java.lang.String.intern. external-general- entities Includes external general (text) entities. external-parameter- entities Includes external parameter entities and the external DTD subset. validation Reports all validation errors (implies external-general- entities and external-parameter-entities). Name Description dom-node Returns the DOM node currently being visited, if SAX is being used as a DOM iterator. If the parser recognizes and supports this property but is not currently visiting a DOM node, returns null. [Read Only] Skonnard.book Page 190 Monday, October 1, 2001 8:57 AM SAX 2.0 191 SAX 6.4 References For more information about Simple API for XML, please go to http://www.megginson.com/SAX/index.html. xml-string Returns the string of characters associated with the current event. If the parser recognizes and supports this property but is not currently parsing text, it should return null. [Read Only] lexical-handler An optional extension handler for lexical events (for example, comments). decl-handler An optional extension handler for DTD-related events other than notations and unparsed entities. Name Description Skonnard.book Page 191 Monday, October 1, 2001 8:57 AM Skonnard.book Page 192 Monday, October 1, 2001 8:57 AM 193 DOM Chapter 7 DOM Level 2 The Document Object Model is a set of abstract programmatic interfaces that project the Infoset of an XML document onto a tree of nodes. The DOM is defined as a set of Object Management Group (OMG) Interface Definition Language (IDL) interface definitions along with a set of Java language bindings and a set of ECMAScript (JavaScript, JScript) language bindings. Various other language bind- ings have been inferred from the IDL; however, this reference covers the Java and VB language bindings. Level 1 of the DOM was standardized prior to namespaces or the Infoset and requires proprietary extensions to be useful for modern XML applications. For that reason, this chapter ignores DOM Level 1 and uses the term DOM as a syn- onym for DOM Level 2. 7.1 DOM UML Figure 7–1 is a quick-reference UML diagram representing the core DOM level 2 interfaces. 7.2 DOM interfaces The DOM interfaces are listed in alphabetical order with a brief description, Java and VB interface definitions, and a table of members. The members table gives the name of the method or property and a short description. In cases when two names appear in the name column, the first is the Java name and the second is the VB name. In many cases, examples are also provided. Skonnard.book Page 193 Monday, October 1, 2001 8:57 AM 194 Essential XML Quick Reference +getNodeName() +getNodeValue() +setNodeValue() +getNodeType() +getParentNode() +getChildNodes() +getFirstChild() +getLastChild() +getPreviousSibling() +getNextSibling() +getAttributes() +getOwnerDocument() +insertBefore() +replaceChild() +removeChild() +appendChild() +hasChildNodes() +cloneNode() +normalize() +isSupported() +getNamespaceURI() +getPrefix() +setPrefix() +getLocalName() +hasAttributes() «interface» Node +hasFeature() +createDocumentType() +createDocument() «interface» DOMImplementation «interface» DocumentFragment +getDocType() +getImplementation() +getDocumentElement() +createElement() +createDocumentFragment() +createTextNode() +createComment() +createCDATASection() +createProcessingInstruction() +createAttribute() +createEntityReference() +getElementsByTagName() +importNode() +createElementNS() +createAttributeNS() +getElementsByTagNameNS() +getElementById() «interface» Document +item() +getLength() «interface» NodeList +getNamedItem() +setNamedItem() +removeNamedItem() +item() +getLength() +getNamedItemNS() +setNamedItemNS() +removeNamedItemNS() «interface» NamedNodeMap +getData() +setData() +getLength() +substringData() +appendData() +insertData() +deleteData() +replaceData() «interface» CharacterData +getName() +getSpecified() +getValue() +setValue() +getOwnerElement() «interface» Attr +getTagName() +getAttribute() +setAttribute() +removeAttribute() +getAttributeNode() +setAttributeNode() +removeAttributeNode() +getElementsByTagName() +getAttributeNS() +setAttributeNS() +removeAttributeNS() +getAttributeNodeNS() +setAttributeNodeNS() +getElementsByTagNameNS() +hasAttribute() +hasAttributeNS() «interface» Element +splitText() «interface» Text «interface» Comment «interface» CDATASection +getName() +getEntities() +getNotations() +getPublicId() +getSystemId() +getInternalSubset() «interface» DocumentType +getPublicId() +getSystemId() «interface» Notation +getPublicId() +getSystemId() +getNotationName() «interface» Entity «interface» EntityReference +getTarget() +getData() +setData() «interface» ProcessingInstruction «exception» DOMException Figure 7–1 DOM level 2 interface hierarchy. Skonnard.book Page 194 Monday, October 1, 2001 8:57 AM DOM Level 2 195 DOM 7.2.1 Attr The Attr interface models an attribute in an XML document providing access to the various properties of the attribute. Despite extending the Node interface, attribute nodes are not considered part of the DOM tree. Java definition package org.w3c.dom; public interface Attr extends Node { public String getName(); public boolean getSpecified(); public String getValue(); public void setValue(String value) throws DOMException; public Element getOwnerElement(); } VB definition 'IXMLDOMAttribute Property name As String 'readonly Property value As Variant Member Description getName name Returns the QName of the attribute. getSpecified Returns true if the attribute was specified in the original document. Returns false if the attribute is present because of a default value in a DTD. getValue value Retrieves an attribute’s value. setValue value Sets the value of an attribute. getOwnerElement Returns a reference to the Element node that owns the attribute or null if the attribute is currently unowned. An example of an unowned attribute node would be one that had just been created but not yet attached to a particular element. Skonnard.book Page 195 Monday, October 1, 2001 8:57 AM 196 Essential XML Quick Reference Examples Accessing the name and value of an attribute These examples check the name of an attribute, retrieve the value, and finally return the owner element. In addition, the Java example checks whether the attribute was specified or defaulted in by the DTD. Java VB Element ProcessAttributeAndReturnOwnerElement ( Attr att ) { if ( att.getName().equals ( "id" )) { // Retrieve attribute value String value = att.getValue(); // Process employee id // } if ( att.getSpecified() == true ) { // attribute was specified in instance document // rather than being defaulted in from a DTD } return att.getOwnerElement(); } Sub ProcessAttribute ( att As IXMLDOMAttribute ) If att.name = "id" Then ' Retrieve attribute value Dim value As String value = att.value ' Process employee id ' End If End Sub Skonnard.book Page 196 Monday, October 1, 2001 8:57 AM DOM Level 2 197 DOM 7.2.2 CDATASection The CDATASection interface is a signature interface (it adds no further methods to org.w3c.dom.Text ). It is used to denote a text node in the tree that was either read from a CDATA section or should be written as a CDATA section, or both. 7.2.3 CharacterData There are no CharacterData nodes in a DOM tree. Rather, the CharacterData interface provides a base interface for the org.w3c.dom.Text and org.w3c.dom.Comment node types. It provides methods for retrieving and manipulating the character data in these nodes. Java definition package org.w3c.dom; public interface CharacterData extends Node { public String getData() throws DOMException; public void setData(String data) throws DOMException; public int getLength(); public String substringData(int offset, int count) throws DOMException; public void appendData(String arg) throws DOMException; public void insertData(int offset, String arg) throws DOMException; public void deleteData(int offset, int count) throws DOMException; public void replaceData(int offset, int count, String arg) throws DOMException; } VB definition ' IXMLDOMCharacterData Property data As String Property length As Long ' read-only Function substringData ( offset As Long, count As Long ) _ As String Sub appendData ( data As String ) Sub insertData ( offset As Long, data As String ) Sub deleteData ( offset As Long, count As Long ) Skonnard.book Page 197 Monday, October 1, 2001 8:57 AM [...]... Function addElementAndGetList ( doc As IXMLDOMDocument ) _ As IXMLDOMNodeList Dim docelt As IXMLDOMElement Set docelt = doc. documentElement Dim e As IXMLDOMElement Set e = doc. createNode(NODE_ELEMENT, "employee", _ "urn:develop-com:employees") docelt.appendChild e Dim a As IXMLDOMAttribute Set a = doc. createNode(NODE_ATTRIBUTE, "id", "") Dim t As IXMLDOMText Set t = doc. createTextNode("5") a.appendChild t... resulting DocumentType node is not very useful createDocument Creates a Document node of the specified DocumentType along with the document Element Examples Creating the document element This example shows creating a DocumentType node, the Document node, and the document element The resulting XML document could be serialized as follows: Java Document CreateDocument ( DOMImplementation dom ) { DocumentType... elementId); } VB definition ' IXMLDOMDocument Property docType As IXMLDOMDocumentType ' read-only Property implementation As IXMLDOMImplementation ' read-only Property documentElement As IXMLDOMElement Function createElement ( tagName As String ) _ As IXMLDOMElement Function createDocumentFragment() As IXMLDOMDocumentFragment Function createTextNode ( data As String ) As IXMLDOMText Skonnard.book Page... IXMLDOMDocument ) Dim emps As IXMLDOMElement Dim emp1 As IXMLDOMElement Dim emp2 As IXMLDOMElement Dim t As IXMLDOMText ' Remove current document element doc. removeChild doc. documentElement ' Create document element Set emps = doc. createNode ( NODE_ELEMENT, _ "e:employees", "urn:develop-com:employees" ) doc. appendChild emps ' Create first child element and append Set emp1 = doc. createNode ( NODE_ELEMENT,... TEXT_NODE CDATA_SECTION_NODE ENTITY _REFERENCE_ NODE ENTITY_NODE PROCESSING_INSTRUCTION_ short COMMENT_NODE = = = = = = 1; 2; 3; 4; 5; 6; = 7; = 8; DOM 7.2.13 Node Skonnard.book Page 2 16 Monday, October 1, 2001 8:57 AM 2 16 Essential XML Quick Reference public static final short DOCUMENT_NODE = 9; public static final short DOCUMENT_TYPE_NODE = 10; public static final short DOCUMENT_FRAGMENT_NODE = 11; public... emps = doc. createElementNS ( "urn:develop-com:employees", "e:employees" ); doc. appendChild ( emps ); Skonnard.book Page 222 Monday, October 1, 2001 8:57 AM 222 Essential XML Quick Reference emp2 = doc. createElementNS ( "urn:develop-com:employees", "e:employee" ); t = doc. createTextNode ( "Aaron" ); emp2.appendChild ( t ); emps.insertBefore ( emp2, emp1 ); } VB Sub CreateNodes ( doc As IXMLDOMDocument... e.getAttributeNode ( "p:units" ) Is Nothing Then Dim doc As IXMLDOMDocument Set doc = e.ownerDocument Dim a As IXMLDOMAttribute Set a = doc. createNode ( NODE_ATTRIBUTE, "p:units", _ "urn:example-org:weightsandmeasures" ) a.value = "inches" e.setAttributeNode a End If End Sub Skonnard.book Page 212 Monday, October 1, 2001 8:57 AM 212 Essential XML Quick Reference Property notationName As String ' read-only... Property attributes As IXMLDOMNamedNodeMap ' read-only Function insertBefore ( ByRef newChild As IXMLDOMNode, _ ByRef refChild As Variant ) As IXMLDOMNode Function replaceChild ( ByRef newChild As IXMLDOMNode, _ ByRef oldChild As IXMLDOMNode ) As IXMLDOMNode Function removeChild ( ByRef childNode As IXMLDOMNode ) _ As IXMLDOMNode Function appendChild ( ByRef newChild As IXMLDOMNode ) _ As IXMLDOMNode Function... 200 Monday, October 1, 2001 8:57 AM 200 Essential XML Quick Reference Java definition package org.w3c.dom; public interface Document extends Node { public DocumentType getDoctype(); public DOMImplementation getImplementation(); public Element getDocumentElement(); public Element createElement(String tagName) throws DOMException; public DocumentFragment createDocumentFragment(); public Text createTextNode(String... Element docelt = doc. getDocumentElement(); Element e = doc. createElementNS ( "urn:develop-com:employees", "employee" ); docelt.appendChild ( e ); Attr a = doc. createAttributeNS ( null, "id" ); Text t = doc. createTextNode ( "5" ); a.appendChild ( t ); e.setAttributeNodeNS ( a ); return doc. getElementsByTagNameNS ( "urn:develop-com:employees", "employee" ); } VB Function addElementAndGetList ( doc As IXMLDOMDocument . October 1, 2001 8:57 AM 204 Essential XML Quick Reference Java VB NodeList addElementAndGetList ( Document doc ) { Element docelt = doc. getDocumentElement(); Element e = doc. createElementNS ( "urn:develop-com:employees",. definition ' IXMLDOMDocument Property docType As IXMLDOMDocumentType ' read-only Property implementation As IXMLDOMImplementation ' read-only Property documentElement As IXMLDOMElement. useful. createDocument Creates a Document node of the specified DocumentType along with the document Element. Document CreateDocument ( DOMImplementation dom ) { DocumentType dt = dom.createDocumentType