Abstract: This paper introduces the methods and applications for merging XML documents in XML applications. It has broad application prospects in XML-based applications.
Keywords: XML document parser Elements
In XML applications, the most common and practical way is to read and write XML files. Because the XML syntax is strict and the start tag must be paired, merging XML documents is not as simple as merging common files. In Java, the following describes how to merge XML documents.
Design Philosophy
Use the parser in the javax. xml. parsers package to parse the root elements of the two XML files, and then copy the elements of the merged files one by one in recursive mode.
Implementation Process
To read and write XML files, you need to import the following Java package. "//" is followed by a comment. The author's environment is JDK 1.3.1, which is also tested in JDK 1.4.0.
Import java. Io. *; // Basic Java package, including various Io operations
Import java. util. *; // Basic Java package, including various standard data structure operations
Import javax. xml. parsers. *; // XML Parser Interface
Import org. W3C. Dom. *; // Dom Implementation of XML
Import org. Apache. Crimson. Tree. xmldocument; // used to write XML files
Import javax. xml. Transform .*;
Import javax. xml. Transform. Dom .*;
Import javax. xml. Transform. Stream .*;
The following describes the process of merging XML documents. First, describe the functions of each method. The method is merging () has two parameters (the target XML file name and the merged XML file name) and calls the Java parser, obtain the document structure and root element of the Two XML documents to be merged, and call the METHOD Duplicate () and method write (). Of course, some other judgment conditions can be added to the XML document merging process, for example, how to process the merged XML document if it does not exist.
Private Boolean is merging (string mainfilename, string sub filename) throws exception {
Boolean isover = false;
Documentbuilderfactory DBF = documentbuilderfactory. newinstance ();
Document builder DB = NULL;
Try {
DB = DBF. newdocumentbuilder ();
} Catch (parserconfigurationexception PCE ){
System. Err. println (PCE); // output exception information when an exception occurs.
}
Document doc_main = NULL, doc_vice = NULL;
// Obtain the document of Two XML files.
Try {
Doc_main = dB. parse (mainfilename );
Doc_vice = dB. parse (sub filename );
} Catch (DOM exception DOM ){
System. Err. println (DOM. getmessage ());
} Catch (exception IOE ){
System. Err. println (IOE );
}
// Obtain the root element of two files.
Element root_main = doc_main.getdocumentelement ();
Element root_vice = doc_vice.getdocumentelement ();
// Add each element under the root node of the merged file below
Novelist message items = root_vice.getchildnodes ();
Int item_number = messageitems. getlength ();
// If the first element under the root node is removed, for example, <management system>, the I starts from 3. Otherwise, I starts from 1.
For (INT I = 1; I <item_number; I = I + 2 ){
// Call dupliate () to copy the elements under the root node of the merged XML document in sequence.
Element messageitem = (element) messageitems. item (I );
Isover = dupliate (doc_main, root_main, messageitem );
}
// Call write to () to write the merged document to the target XML document.
Boolean iswritten = write to (doc_main, mainfilename );
Return isover & iswritten;
}
The dupliate () method has three parameters (the document of the target XML document, the parent node of the node to be added to the target XML document and the copy node of the merged XML document ), recursively copy the elements in an XML document to another XML document.
Private Boolean dupliate (document doc_dup, element father, element son) throws exception {
Boolean is done = false;
String son_name = Son. getnodename ();
Element sub item = doc_dup.createelement (son_name );
// Copy node attributes
If (son. hasattributes ()){
Namednodemap attributes = Son. getattributes ();
For (INT I = 0; I <attributes. getlength (); I ++ ){
String attribute_name = attributes. Item (I). getnodename ();
String attribute_value = attributes. Item (I). getnodevalue ();
Subitem. setattribute (attribute_name, attribute_value );
}
}
Father. appendchild (sub item );
// Copy node Value
Text Value son = (text) Son. getfirstchild ();
String nodevalue_root = "";
If (value_son! = NULL & value_son.getlength ()> 0) nodevalue_root = (string) value_son.getnodevalue ();
Text valuenode_root = NULL;
If (nodevalue_root! = NULL) & (nodevalue_root.length ()> 0) valuenode_root = doc_dup.createtextnode (nodevalue_root );
If (valuenode_root! = NULL & valuenode_root.getlength ()> 0) subitem. appendchild (valuenode_root );
// Copy the subnode
Novelist sub_messageitems = Son. getchildnodes ();
Int sub_item_number = sub_messageitems.getlength ();
If (sub_item_number <2 ){
// If no subnode exists, return
Is done = true;
}
Else {
For (Int J = 1; j <sub_item_number; j = J + 2 ){
// If a subnode exists, call this method recursively.
Element sub_messageitem = (element) sub_messageitems.item (j );
Is done = dupliate (doc_dup, subitem, sub_messageitem );
}
}
Return is done;
}
The writeto () method has two parameters (the document and file name of the target XML file), which write the obtained target XML file into the file.
Private Boolean write to (document DOC, string filename) throws exception {
Boolean isover = false;
Dom source DOMs = new Dom source (DOC );
File F = new file (filename );
Stream result sr = new stream result (f );
Try
{
Transformer Factory TF = transformerfactory. newinstance ();
Transformer T = TF. newtransformer ();
Properties Properties = T. getoutputproperties ();
Properties. setproperty (outputkeys. encoding, "gb2312 ");
T. setoutputproperties (properties );
T. Transform (DOMS, Sr );
Isover = true;
}
Catch (transformerconfigurationexception TCE)
{
TCE. printstacktrace ();
}
Catch (transformer exception Te)
{
Te. printstacktrace ();
}
Return isover;
}
Finally, use the test function for testing. For two existing XML files (for example, the existing file D:/. XML and D:/B. XML. XML to. XML), you can test as follows:
Public static void main (string [] ARGs) throws exception {
Boolean is done = is merging ("D:/a. xml", "d:/B. xml ");
If (is done) system. Out. println ("XML files have been merged .");
Else system. Out. println ("XML files have not been merged .");
}
Summary
This article describes how to use the XML parser in Java to merge two XML documents. Of course, you can add other constraints during the merge process, such as filtering out specific elements. In addition, the insert position of the copied element can be limited.