The parser establishes tree structure data corresponding to the XML structure in the memory, so that the application can conveniently obtain data in the XML file. JAXP also provides an API for creating an XML file using the tree structure data in the memory, that is, using the document object obtained by the parser to create a new XML file.
1. Transformer object
We already know that the parse method of the parser encapsulates the parsed XML file into a document node and returns it. We can modify the document node, then, use the transformer object to convert a document node into an XML file.
Even if the parser does not call the parse method, a document node can be obtained. The parser can obtain a document node by calling newdocument (), for example:
Document document = builder. newdocument ();
The application can modify such a document node and then use the transformer object to convert a document node into an XML file.
To use a transformer object to transform a document node into an XML file, follow these steps.
Use the transformerfactory class in the javax. xml. Transform package to create an object:
Transformerfactory transfactory = transformerfactory. newinstance ()
The transfactory object obtained in the step calls the newtransformer () method to obtain a transformer object:
Transformer transformer = transfactory. newtransformer ();
The transformer class is in the javax. xml. Transform package.
Encapsulate the transformed document object into a domsource object:
Domsource = new domsource (document );
The domsource class is in the javax. xml. Transform. Dom package.
Encapsulate the transformed XML file object into a streamresult object:
File file = new file ("newxml. xml ");
Fileoutputstream out = new fileoutputstream (File );
Streamresult xmlresult = new streamresult (out );
The streamresult class is in the javax. xml. Transform. Stream package.
Finally, the transformer object transformer calls the transform method to implement the transformation:
Transformer. Transform (domsource, xmlresult );
2. Common Methods for modifying document
The node interface is the parent interface of document and provides many methods to modify, add, and delete nodes:
The node appendchild (node newchild) node calls this method to add a new subnode to the current node and return the new node.
Node removechild (node oldchild) throws domexception node calls this method to delete the child node specified by the parameter and return the deleted child node.
The node replaceChild (node newchild, node oldchild) node can call this method to replace the child node and return the child node to be replaced.
In addition to methods inherited from the node interface, the element interface also provides methods for adding nodes:
ATTR removeattributenode (ATTR oldattr) deletes attributes of the element node.
Void setattribute (string name, string value) adds new attributes and attribute values to the element node. If the attribute already exists, the new attribute replaces the old one.
In addition to the methods inherited from the node interface, the text interface also provides methods for modifying node content:
Text replacewholetext (string content) replaces the text content of the current text node.
Void appenddata (string Arg) adds text content to the end of the current text node.
Void insertdata (INT offset, string Arg) inserts text content into the current text node. The insertion position is specified by the offset parameter, that is, the subsequent position of the nth offset character.
Void deletedata (INT offset, int count) deletes part of the text content of the current node. The deleted range is specified by the offset and count parameters, that is, the Count characters after the offset character.
Void replacedata (INT offset, int count, string Arg) replaces Part Of The text content in the current text node with the content specified by the ARG parameter. The replaced range is specified by the offset and count parameters, that is, the Count characters after the offset character.
3. Use Dom to create an XML file
In Example 10 below, the parser parses an XML file: "cha6_10.xml", modifies the document object, and uses transformer to obtain a new XML file: "newxml. xml ".
Example 10 Cha6_10.xml <? XML version = "1.0" encoding = "UTF-8"?> <Exam transcript> <Advanced mathematics> <Examinee Name> Zhang San </examinee Name> <Score> 89 </score> </Advanced mathematics> <Advanced mathematics> <Examinee Name> Li Si </examinee Name> <Score> 66 </score> </Advanced mathematics> </Test transcript> Jaxp53. Java Import javax. xml. Transform .*; Import javax. xml. Transform. Stream .*; Import javax. xml. Transform. Dom .*; Import org. W3C. Dom .*; Import javax. xml. parsers .*; Import java. Io .*; Public class jaxp53 { Public static void main (string ARGs []) { Modifynode modify = new modifynode (); Try { Documentbuilderfactory factory = Documentbuilderfactory. newinstance (); Documentbuilder builder = factory. newdocumentbuilder (); Document document = builder. parse (new file ("cha6_10.xml ")); Element root = Document. getdocumentelement (); Nodelist = root. getchildnodes (); Modify. modifynode (nodelist ); Transformerfactory transfactory = transformerfactory. newinstance (); Transformer transformer = transfactory. newtransformer (); Domsource = new domsource (document ); File file = new file ("newxml. xml "); Fileoutputstream out = new fileoutputstream (File ); Streamresult xmlresult = new streamresult (out ); Transformer. Transform (domsource, xmlresult ); } Catch (exception E) { System. Out. println (E ); } } } Class modifynode { Int m = 0; Public void modifynode (nodelist) { Int size = nodelist. getlength (); For (int K = 0; k <size; k ++) { Node node = nodelist. Item (k ); If (node. getnodetype () = node. text_node) { Text textnode = (text) node; Int length = textnode. getlength (); String STR = textnode. getwholetext (). Trim (); Try { Double D = double. parsedouble (STR ); If (D> = 90 & D <= 100) Textnode. insertdata (length, "(excellent dd show )"); Else if (D> = 80 & D <90) Textnode. insertdata (length, "(good )"); Else if (D> = 60 & D <80) Textnode. insertdata (length, "(PASS )"); Else Textnode. insertdata (length, "(fail )"); } Catch (numberformatexception ee) {} } If (node. getnodetype () = node. element_node) { Element elementnode = (element) node; String name = elementnode. getnodename (); If (elementnode. haschildnodes ()) { Elementnode. setattribute ("Exam nature", "Closed exam "); } Nodelist nodes = elementnode. getchildnodes (); Modifynode (nodes ); } } } } The content of the XML file "newxml. xml" obtained in Example 10 is as follows: Newxml. xml <? XML version = "1.0" encoding = "UTF-8"?> <Exam transcript> <Advanced mathematics test nature = "Closed exam"> <Name of the examinee = "Closed exam"> Michael Zhang </Name of the examinee> <Score Test type = "Closed exam"> 89 (good) </score> </Advanced mathematics> <Advanced mathematics test nature = "Closed exam"> <Name of the examinee = "Closed exam"> Li Si </Name of the examinee> <Score Test type = "Closed exam"> 66 (PASS) </score> </Advanced mathematics> </Test transcript> |
The Dom parser in Example 10 generates a Document Object using a known XML file, and then modifies the document object in the memory to generate a new XML file. In Example 11 below, the DOM parser calls newdocument () to get a Document Object, "javaeleven. the XML file generated by Java is "train timetable. XML ", open it in a browser. The effect is 6.12.
|
Figure 6.12 XML file generated using dom |
Example 11 Jaxpeleven. Java Import javax. xml. Transform .*; Import javax. xml. Transform. Stream .*; Import javax. xml. Transform. Dom .*; Import org. W3C. Dom .*; Import javax. xml. parsers .*; Import java. Io .*; Public class jaxpeleven { Public static void main (string ARGs []) { Try { String train [] = {"t126 Times", "k256 Times", "l345 times "}, Type [] = {"Express", "General express", "Linke "}, Starttime [] = {"18:36", "22:56", "10:12 "}; Documentbuilderfactory factory = Documentbuilderfactory. newinstance (); Documentbuilder builder = factory. newdocumentbuilder (); Document document = builder. newdocument (); Document. setxmlversion ("1.0 "); Element Train Timetable = Document. createelement ("Train Timetable "); Document. appendchild (Train Timetable ); For (int K = 1; k <= train. length; k ++) { Train Timetable. appendchild (document. createelement ("train times ")); } Nodelist = Document. getelementsbytagname ("train "); Int size = nodelist. getlength (); For (int K = 0; k <size; k ++) { Node node = nodelist. Item (k ); If (node. getnodetype () = node. element_node) { Element elementnode = (element) node; Elementnode. setattribute ("category", type [k]); Elementnode. appendchild (document. createelement ("name ")); Elementnode. appendchild (document. createelement ("driving time ")); } } Nodelist = Document. getelementsbytagname ("name "); Size = nodelist. getlength (); For (int K = 0; k <size; k ++) { Node node = nodelist. Item (k ); If (node. getnodetype () = node. element_node) { Element elementnode = (element) node; Elementnode. appendchild (document. createtextnode (train [k]); } } Nodelist = Document. getelementsbytagname ("driving time "); Size = nodelist. getlength (); For (int K = 0; k <size; k ++) { Node node = nodelist. Item (k ); If (node. getnodetype () = node. element_node) { Element elementnode = (element) node; Elementnode. appendchild (document. createtextnode (Starttime [k]); } } Transformerfactory transfactory = transformerfactory. newinstance (); Transformer transformer = transfactory. newtransformer (); Domsource = new domsource (document ); File file = new file ("Train Timetable. xml "); Fileoutputstream out = new fileoutputstream (File ); Streamresult xmlresult = new streamresult (out ); Transformer. Transform (domsource, xmlresult ); } Catch (exception E) { System. Out. println (E ); }
} } |