1.CDATA Zone
When writing an XML file, some content may not want the parsing engine to parse execution, but rather as raw content processing.
In this case, the content can be placed in a CDATA area, and for content within a CDATA region, the XML parser does not process, but is directly intact output.
Syntax: <! [Cdata[content]]>
<! [cdata[
<book>
<br/>
</book>
]]>
2. Processing instructions
Processing instructions, referred to as pi (processing instruction). The processing instruction is used to direct the parsing engine to parse the XML document content.
For example, you can use the Xml-stylesheet directive in an XML document to notify the XML parsing engine and apply a CSS file to display XML document content. To be blunt, XML uses styles <?xml-stylesheet type= "text/css" href= "1.css"?>
The processing instructions must be "<?" At the beginning, with "?>" as the end, the XML declaration statement is the most common kind of processing instruction.
3.XML Constraints Overview
What is an XML constraint
In XML technology, you can write a document to constrain the writing specification of an XML document, which is called an XML constraint.
The commonly used constraint technology
(1) XML DTD
A DTD (document type definition), which is called a type definition, is a DTD file that constrains the writing of an XML document's nodes, attributes, and so on.
(2) XML Schema, which is an XML-based DTD replacement.
The XML Schema file itself is an XML file, but its extension is usually. xsd
As with an XML file, an XML Schema document must have a root node, but the name of the root element is schema.
XML Schemas are created with a set of pre-defined XML elements and attributes that define the structure and content patterns of the XML document. XML Schema Specifies the structure of an XML document instance and the data type of each element/attribute
4.JavaBean
is an entity class, custom object, need to have a set of get and set methods, the default constructor must exist
5.XML parsing
An overview of XML parsing techniques
There are two ways to parse XML: DOM and sax
DOM: (The Document Object model, or the file-objects models) is a way of parsing XML that is recommended by the Organization.
Sax: (Simple API for XML) is not an official standard, but it is the de facto standard of the XML community, which is supported by almost all XML parsers.
XML Parser
Crimson (Sun), Xerces (IBM), Aelfred2 (dom4j)
XML Parsing Development Package
Jaxp (Sun), Jdom, dom4j, Pull (Android SDK comes with)
(1) Jaxp-dom parsing XML (curd)
JAXP (Java API for XML processing)
JAXP is a set of XML parsing APIs provided by Sun
Jaxp is a good way to support DOM and sax parsing
The JAXP development Pack is part of the J2SE, including the following packages or sub-packages
Javax.xml
Org.w3c.dom
Org.xml.sax
In the Javax.xml.parsers package, several factory classes are defined, and the programmer calls these factory classes to get the parser object for DOM or SAX parsing the XML document
Book.java
Package com.yxl.xml;
/**
* Custom Object--javabean
* * requires a special set of methods: GetXxx and Setxxx
* * Must have a default construction method
*
* ALT + SHIFT + S
*/
public class Book {
Private String ID;
Private String title;
Private String Price;
Public String getId () {
return this.id;
}
public void SetId (String id) {
This.id = ID;
}
Public String GetTitle () {
return title;
}
public void Settitle (String title) {
This.title = title;
}
Public String GetPrice () {
return price;
}
public void Setprice (String price) {
This.price = Price;
}
Public book () {
}
Public book (string ID, string title, String price) {
This.id = ID;
This.title = title;
This.price = Price;
}
@Override
Public String toString () {
Return "book [id=" + ID + ", price=" + Price + ", title=" + title + "]";
}
}
Books.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<books>
<book id= "b001" >
<title>java Core Technology </title>
<price>98000</price>
</book>
<book id= "b002" >
<title>thinking in Java</title>
<price>22000</price>
</book>
</books>
Inquire
Package com.yxl.xml;
Import java.util.ArrayList;
Import java.util.List;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;
public class MainClass {
public static void Main (string[] args) throws Exception {
System.out.println (Getallbook ());
}
/*
* Get all the books and save all the book contents list
*/
public static List Getallbook () throws exception{
Create a list to hold all the data
List allbooklist = new ArrayList ();
/* Query the required data from the XML document and replace the simulation data */
Get the Instance Factory
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Get resolved
Documentbuilder builder = Factory.newdocumentbuilder ();
Get document-Parse XML document Java.io.FileNotFoundException
Document document = Builder.parse ("books.xml"); Refers to a file under the root path of a Java project
Get all the book elements
NodeList bookelements = document.getElementsByTagName ("book");
Traverse all the book elements
for (int i = 0; i < bookelements.getlength (); i++) {
Get every element of the book
Node node = Bookelements.item (i);
Node.getattributes (); --Get all the properties
Element Bookele = (element) node;
Gets the property value of the specified name ID
String id = bookele.getattribute ("id");
String title = "";
String price = "";
Query the title and price
Gets all the child nodes of the current book element
NodeList childlist = Bookele.getchildnodes ();
System.out.println (id + ":" + childlist.getlength ());
Traverse all The Children
for (int c = 0; c < childlist.getlength (); C + +) {
Get all the kids
Node Childnode = Childlist.item (c);
Element child = (element) Childnode; Java.lang.ClassCastException:
Get node Name
String childname = Childnode.getnodename ();
Judge whether the title
if (Childname.equals ("title"))
if ("title". Equals (ChildName)) {
Get title Content
title = Childnode.gettextcontent ();
}
Determine if it is price
if ("Price". Equals (ChildName)) {
Price = Childnode.gettextcontent ();
}
}
Create JavaBean Book Object
Book book = new book ();
Book.setid (ID);
Book.setprice (price);
Book.settitle (title);
Adds an object book that holds all the data to the list
Allbooklist.add (book);
}
return allbooklist;
}
}
Delete and change
Package com.yxl.xml;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import Javax.xml.transform.Result;
Import Javax.xml.transform.Source;
Import Javax.xml.transform.Transformer;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;
public class Cudtest {
public static void Main (string[] args) throws exception{
Save the document in memory to the Books.jasp.xml file
Document document = Cudtest.getdocument ();
Modify the contents of document: Add, Delete, modify
Add to
/* Content to add
* <book id= "b002" >
<title>thinking in Java</title>
<price>22000</price>
</book>
* For who to add: root element Books
*/
Get Books root element
Element rootelement = Document.getdocumentelement ();
Create book Element
Element Newbook = document.createelement ("book");
Setting the ID Property
Newbook.setattribute ("id", "b003");
Create Title Element
Element titleelement = document.createelement ("title");
Adds the title element to the new book element
Newbook.appendchild (titleelement);
Add a value to the title
Titleelement.settextcontent ("Phoenix sister Photo");
Add the book element to the books root element
Rootelement.appendchild (Newbook);
Save
SaveXML (document);
}
private void Delete () throws exception{
Save the document in memory to the Books.jasp.xml file
Document document = Cudtest.getdocument ();
Modify the contents of document: Add, Delete, modify
Delete <book id= "b001" >
Get all the books
NodeList Booklist = document.getElementsByTagName ("book");
for (int n = 0; n < booklist.getlength (); n + +) {
Get every book
Node Booknode = Booklist.item (n);
Get the value of ID
Element bookelement = (element) Booknode;
String id = bookelement.getattribute ("id");
Judge Book id = = b001
if ("b001". Equals (ID)) {
Delete bookelement current node, call parent node, do action
Get parent Node
Node parent = Bookelement.getparentnode ();
Operation
Parent.removechild (bookelement);
}
}
Save
SaveXML (document);
}
private void Update () throws exception{
Save the document in memory to the Books.jasp.xml file
Document document = Cudtest.getdocument ();
Modify the contents of document: Add, Delete, modify
Modify <book id= "b001" ><title>java Core technology </title>--"Java core"
Get all the books
NodeList Booklist = document.getElementsByTagName ("book");
for (int n = 0; n < booklist.getlength (); n + +) {
Get every book
Node Booknode = Booklist.item (n);
Get the value of ID
Element bookelement = (element) Booknode;
String id = bookelement.getattribute ("id");
Judge Book id = = b001
if ("b001". Equals (ID)) {
Get all the title
NodeList childlist = bookelement.getelementsbytagname ("title");
Get only one title
Node title = Childlist.item (0);
Get title
System.out.println (Title.gettextcontent ());
Setting the value
Title.settextcontent ("Java Core");
}
}
Save
SaveXML (document);
}
private static void SaveXML (document document) throws Exception {
Obtaining a Persisted object instance factory
Transformerfactory factory = Transformerfactory.newinstance ();
Getting persisted objects
Transformer Transformer = Factory.newtransformer ();
Save the memory data to the hard disk
Source: Document encapsulates document to source
Source Xmlsource = new Domsource (document);
Result: Books.jasp.xml "file path" is encapsulated into result
Result outputtarget = new Streamresult ("Books.jasp.xml");
Transformer.transform (Xmlsource, outputtarget);
System.out.println ("Done");
}
/**
* Get Document Object
* @return
*/
public static Document GetDocument () throws exception{
Get Factory examples
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Get parser
Documentbuilder builder = Factory.newdocumentbuilder ();
Get document
Document document = Builder.parse ("books.xml");
return document;
}
}
(2) Jaxp-sax parsing xml
Sax parsing principle
SAX is an event-driven XML processing method
Scan the document line by row, parsing while scanning
In sax, it's a complex operation.
Extend the Org.xml.sax.helpers.DefaultHandler class only if you want to implement a partial interface
Default empty implementation of the DefaultHandler class
Saxtest.java
Package com.yxl.xml;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import Org.xml.sax.helpers.DefaultHandler;
public class Saxtest {
public static void Main (string[] args) throws Exception {
Get an analytic factory instance
SAXParserFactory factory = Saxparserfactory.newinstance ();
Get parser
SAXParser parser = Factory.newsaxparser ();
DefaultHandler dh = new Mydefaulthandler ();
Parsing XML documents
Parser.parse ("books.xml", DH);
System.out.println ("Done");
}
}
Mydefaulthandler.java
Package com.yxl.xml;
Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.helpers.DefaultHandler;
public class Mydefaulthandler extends defaulthandler{
@Override
public void Startdocument () throws Saxexception {
System.out.println ("document Start");
}
@Override
/**
* If the XML file uses schema constraints <xs:element>
* * Uri:schema--targetnamespace
* * Localname--element
* * QName---xs:element
* If you do not use
* * Uri:null
* * Localname:null
* * Qname:element
*
* Attributes: A collection of all the attributes of the current element
*/
public void Startelement (string uri, String localname, String qName,
Attributes Attributes) throws Saxexception {
System.out.println ("element start" + qName + "* * *" + attributes.getvalue ("id"));
}
@Override
public void characters (char[] ch, int start, int length)
Throws Saxexception {
System.out.println (New String (CH, start, length));
}
@Override
public void EndElement (string uri, String localname, String qName)
Throws Saxexception {
System.out.println ("element end:" + qName);
}
@Override
public void Enddocument () throws Saxexception {
System.out.println ("End of document");
}
}
(3) DOM4J parsing XML, developing the recommended use of this
DOM4J is a simple, flexible library of open source code. DOM4J was developed by the people who developed jdom early and then independently. Unlike Jdom, DOM4J uses interfaces and abstract base classes, and although the DOM4J API is relatively complex, it provides greater flexibility than jdom
DOM4J is a very good Java XML API with excellent performance, powerful features, and easy to use features. Many software dom4j, such as Hibernate, including Sun's own JAXM, are now used dom4j
With dom4j development, download the dom4j jar file as appropriate
Refer to the jar package method, create a new folder named Lib under the project root, copy the jar package that will be used to the folder, right-click the build Path,add to build Path for the jar package that you want to use
XML query, referencing Dom4j-1.6.1.jar
Dom4jtest.java
Package com.yxl.xml;
Import java.util.ArrayList;
Import java.util.List;
Import org.dom4j.Document;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader;
public class Dom4jtest {
public static void Main (string[] args) throws Exception {
Need list to store all the book objects
List Allbook = new ArrayList ();
Get Parse Stream
Saxreader reader = new Saxreader ();
Parsing of XML files
Document document = Reader.read ("books.xml");
Get root element
Element rootelement = Document.getrootelement ();
Get all the books
List List = Rootelement.elements ();
Traverse all the books-list
for (int e = 0; e < list.size (); e + +) {
Create book Object
Book book = new book ();
Get every book element
Element bookelement = (Element) List.get (e);
Get the ID property value of a book
String id = bookelement.attributevalue ("id");
SYSTEM.OUT.PRINTLN (ID);
Book.setid (ID);
Get title and price
List childlist = bookelement.elements ();
Traversing child elements
for (int c = 0; c < childlist.size (); C + +) {
Get each child element
Element child = (element) childlist.get (c);
SYSTEM.OUT.PRINTLN (child);
Get child element text content
String content = Child.gettext ();
Determine if it is the title
if ("title". Equals (Child.getname ())) {
Book.settitle (content);
}
Determine if it is price
if ("Price". Equals (Child.getname ())) {
Book.setprice (content);
}
}
Add a book object that already encapsulates the content to the list
Allbook.add (book);
}
Before the program resolves, the output content
System.out.println (Allbook);
}
}
XML query, using XPath expression queries, referencing Dom4j-1.6.1.jar, Jaxen-1.1-beta-6.jar
Xpathtest.java
Package com.yxl.xml;
Import org.dom4j.Document;
Import Org.dom4j.Node;
Import Org.dom4j.io.SAXReader;
public class Xpathtest {
public static void Main (string[] args) throws Exception {
Get document
Get Parse Stream
Saxreader reader = new Saxreader ();
Parsing xml
Document document = Reader.read ("books.xml");
Query the book id = b002 element java.lang.NoClassDefFoundError
Node node = Document.selectsinglenode ("//book[@id = ' b002 ']");
SYSTEM.OUT.PRINTLN (node);
}
}
dom4j additions and deletions change
Package com.yxl.xml;
Import Java.io.FileOutputStream;
Import Org.dom4j.Attribute;
Import org.dom4j.Document;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.Node;
Import Org.dom4j.io.SAXReader;
Import Org.dom4j.io.XMLWriter;
public class Curdtest {
public static void Main (string[] args) throws Exception {
Get document
Get Parse Stream
Saxreader reader = new Saxreader ();
Parsing xml
Document document = Reader.read ("books.xml");
Get root element
Element rootelement = Document.getrootelement ();
Add to
Create book Element
Element Newbook = documenthelper.createelement ("book");
Create id attribute for book element
Attribute idattr = Documenthelper.createattribute (Newbook, "id", "b004");
Add to book element
Newbook.add (IDATTR);
Create Title Element
Element titleelement = documenthelper.createelement ("title");
Setting the value
Titleelement.settext ("Chicken Sister Chao");
Add to Newbook
Newbook.add (titleelement);
Add a new book element to the root element
Rootelement.add (Newbook);
Save the document
Persistent stream
Where to create the output file
FileOutputStream out = new FileOutputStream ("Books.dom4j.xml");
XMLWriter writer = new XMLWriter (out);
Add a Content Object
Writer.write (document);
Close the stream
Writer.close ();
}
public static void Delete (string[] args) throws Exception {
Get document
Get Parse Stream
Saxreader reader = new Saxreader ();
Parsing xml
Document document = Reader.read ("books.xml");
Delete b002
Node Booknode = Document.selectsinglenode ("//book[@id = ' b002 ']");
Get parent Node
Node parent = Booknode.getparent ();
Element parentelement = (element) parent;
Delete operation
Parentelement.remove (Booknode);
Save the document
Persistent stream
Where to create the output file
FileOutputStream out = new FileOutputStream ("Books.dom4j.xml");
XMLWriter writer = new XMLWriter (out);
Add a Content Object
Writer.write (document);
Close the stream
Writer.close ();
}
public static void Update (string[] args) throws Exception {
Get document
Get Parse Stream
Saxreader reader = new Saxreader ();
Parsing xml
Document document = Reader.read ("books.xml");
Modified B002 Price 100
Node Booknode = Document.selectsinglenode ("//book[@id = ' b002 ']");
Strong Turn Conversion
Element bookelement = (element) Booknode;
Get the appropriate element by the specified name
Element priceelement = bookelement.element ("price");
modifying values
Priceelement.gettext ();
Priceelement.settext ("100");
Save the document
Persistent stream
Where to create the output file
FileOutputStream out = new FileOutputStream ("Books.dom4j.xml");
XMLWriter writer = new XMLWriter (out);
Add a Content Object
Writer.write (document);
Close the stream
Writer.close ();
}
}
Java Basic Learning Xmlcdata Zone, XML processing instructions, XML Constraints overview, JavaBean, XML parsing (8)