15.javaweb XML Detailed Tutorial

Source: Internet
Author: User
Tags cdata

I. Introduction to the XML language

1, function: Used to describe and save the actual data with a certain relationship, but also as a software configuration file, and describe the relationship between the program module

2, Syntax:

First look at the components of an XML file

About document Declarations

Version also used for the 1.0 version published in 2000, encoding indicates that the browser in the parsing XML file is encoded, must be consistent with the XML file is encoded, otherwise garbled files will appear, because the XML file is stored in accordance with a coding rule to encode Chinese into binary number, browser re-parse the time Follow this code to parse the binary number into correct Chinese, otherwise an error will be made.

With respect to elements, i.e., tags, an XML document has only one root tag, the label contains the label body <a>***</a> and does not contain the label body <a/> the spaces and line breaks in the tag body are treated as label contents. The naming conventions for labels are as follows

With respect to attributes, a label can have multiple attributes, which consist of property names and values, and the property name naming specification is the same as an element, with the trick "to rewrite a property into a label's sub-label

About annotation:<!--comment-->, note cannot be nested before document declaration

About CDATA Zones

About escape characters

With respect to escaping and CDATA, escaping is the display of special characters in XML, CDATA The reading of the contents of XML to the program.

About processing Instructions

Application

XML file

Results

3, DTD constraints and DTD validation

Overview: In XML technology, you can write a document that constrains the writing specification of an XML document, which is called an XML constraint

Constraint classification: XML dtd,xml Schema

XML DTD

<! DOCTYPE Summer Vacation SYSTEM "BOOK.DTD" > represents referential BOOK.TDT constraints to constrain the writing specification of XML documents

<! ELEMENT Bookshelf (book +) > indicates that there can be multiple "book" sub-tags in the "Bookshelf" tab

<! ELEMENT Book (title, author, price) > means "book" in this label, there should be "title", "Author", "Price" this three sub-tags

<! Element title (#PCDATA) > "title" The contents of this tag should be a string

XML DTD Documentation: DTD constraints can be written either as a single file or in an XML file

The above example is written for a separate file, which is written in an XML file

References to DTD documents

DTD constraint syntax: element definition, attribute definition, entity definition

Element definition

Property Definition

Setup instructions

Property value Type: Enumeration

Property value type: ID

Common property value Types

Entity definition: Concept

Entity definition: Referencing entities

Entity definition: Parameter entity

4, XML programming (CRUD)

XML parsing Technology

About the differences between DOM and sax

Dom parsing is the memory in which the nodes of XML are saved as document objects, and the objects are organized in tree form, so DOM parsing is suitable for adding and removing XML files, but it is more memory consuming.

Sax parsing is a row of read XML file and parsing, so sax parsing memory consumption is small, parsing speed, but not suitable for adding and removing changes

Adjust the JVM's maximum memory size: The JVM default program's maximum memory is 64M, when the program needs to run more memory than this value will be an error

You can set the maximum memory that can be consumed when the program runs by setting a value of 80M

5, JAXP parsing package DOM parsing of XML documents

Note Import the Javax.xml.parsers package

Dom parsing, each component of an XML document is represented by an object, such as a label with element, attributes with attr, but no matter what object is a subclass of node, any node that can be acquired in development is treated as node.

 Packagecom.chen.ying;ImportJava.io.FileOutputStream;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importjavax.xml.parsers.ParserConfigurationException;ImportJavax.xml.transform.Transformer;Importjavax.xml.transform.TransformerFactory;ImportJavax.xml.transform.dom.DOMSource;ImportJavax.xml.transform.stream.StreamResult;ImportJavax.xml.transform.stream.StreamSource;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;ImportOrg.w3c.dom.Node;Importorg.w3c.dom.NodeList; Public classparaseDemo01 { Public Static voidMain (string[] args)throwsException {//1, create factory, get factory instanceDocumentbuilderfactory Factory=documentbuilderfactory.newinstance (); //2, get DOM parser through factoryDocumentbuilder Builder=Factory.newdocumentbuilder (); //3. Parse the XML document to get the Document object representing the documentsDocument Document=builder.parse ("Src/com/chen/ying/country.xml");//best to fill in absolute path//4, the XML document is added and censored//Query NodeNodeList list01=document.getelementsbytagname ("province");//Place query results in the node linked listNode node01=list01.item (1);//get the second element of the linked list;String content01=node01.gettextcontent ();//get the node content.System.out.println ("Information of the provinces to be queried:" +content01); //traverse all nodes.Node node02=document.getelementsbytagname ("Country"). Item (0);//get the root node.Listall (NODE02);//Recursive traversal//queries the specified attribute of the specified node, and if it is known that the query result is an element, it can be received directly with element, which is richer and more accurateElement element01= (Element) document.getelementsbytagname ("province"). Item (0);//get the "Sichuan" junction.String Value=element01.getattribute ("id");//property value obtained by property nameSystem.out.println (value); //add nodes to the XML "Sichuan" node:<city> Suining </city>Element City=document.createelement ("City"); City.settextcontent ("Suining");//Create a node and add content to the node.Element province01= (Element) document.getelementsbytagname ("province"). Item (0); Province01.appendchild (city);//to hang the created node under the specified nodes//Add a node to a specified location:<city> Lijiang </city>Element insertcity=document.createelement ("City"); Insertcity.settextcontent ("Lijiang");//Create a node and add content to the node.//Get hanging child nodesElement province02= (Element) document.getelementsbytagname ("province"). Item (1); //get the location reference nodeElement localcity= (Element) province02.getelementsbytagname ("City"). Item (1); //inserts a node to a specified position on a hanging child nodeProvince02.insertbefore (insertcity, localcity); //to add a property to a specified nodeElement01.setattribute ("Maincity", "Chengdu");//Add properties for the Sichuan node//Delete the specified node and properties: Deleting the specified node needs to find the node and the parent node of the nodeElement province03= (Element) document.getelementsbytagname ("province"). Item (2);               Province03.getparentnode (). removechild (PROVINCE03); //Update node content: Find the nodes that need to be updated and then reset the contentElement city01= (Element) document.getelementsbytagname ("City"). Item (0); City01.settextcontent (Mianyang); //writes updated memory back to the hard drive area of the XML documenttransformerfactory tfactory=transformerfactory.newinstance (); Transformer TF=Tfactory.newtransformer (); Tf.transform (NewDomsource (document),NewStreamresult (NewFileOutputStream ("Src/com/chen/ying/country.xml"))); }     Public Static voidListall (node node) {if(nodeinstanceofElement) {//Print If the node is an element (parsing will resolve all content within a node into an object) .System.out.println (node); } NodeList List=node.getchildnodes ();//get all the sub-nodes under a node, including spaces         for(intI=0;i<list.getlength (); i++) {Listall (List.item (i));//Recursive traversal        }    }}

XML document

  <?XML version= "1.0" encoding= "UTF-8"?><Country>    <ProvinceID= "Sichuan">  <!--Provinces -         < City>Chengdu</ City>         < City>Guang'an</ City>         < City>Nanchong</ City>    </Province>    <ProvinceID= "Yunnan">         < City>Chuxiong</ City>         < City>Kunming</ City>         < City>Dali</ City>    </Province>    <ProvinceID= "Zhejiang">         < City>Hangzhou</ City>         < City>Ningbo</ City>    </Province></Country>

Case practice, using XML files as a database to save student scores and other information, and then use DAO to do the increase and deletion check

6, Sax parsing

15.javaweb XML Detailed Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.