When processing XML in Java, read and process the XML document. This is an instance code.
Import java. Io. fileinputstream;
Import javax. xml. parsers .*;
Import org. W3C. Dom .*;
/*
* Created on 2004-6-2
* Java reads XML documents
* Use Dom to read and print the content of an XML document.
*/
Public class testxml {
Public static void main (string [] ARGs ){
Document Doc;
Documentbuilderfactory factory;
Documentbuilder docbuilder;
Element root;
String elementname;
Fileinputstream in;
String filename;
Try {
// Get the XML file
Filename = system. getproperty ("user. dir ");
Filename = filename + "/sample. xml ";
In = new fileinputstream (filename );
// Parse the XML file and generate the Document Object
Factory = documentbuilderfactory. newinstance ();
Factory. setvalidating (false );
Docbuilder = factory. newdocumentbuilder ();
Doc = docbuilder. parse (in );
// Resolution successful
System. Out. println ("parse successfull ");
// Obtain the root node of the XML document
Root = Doc. getdocumentelement ();
Elementname = root. getnodename ();
// Print the attributes of the Root Node
Printattributes (Root );
// Print all nodes of this document
System. Out. println ("print all nodes ");
Printelement (root, 0 );
}
Catch (exception exp ){
Exp. printstacktrace ();
}
}
// Print all attributes of a node
Public static void printattributes (element ELEM ){
Namednodemap attributes;
Int I, Max;
String name, value;
Node curnode;
Attributes = ELEM. getattributes ();
Max = attributes. getlength ();
For (I = 0; I <Max; I ++ ){
Curnode = attributes. item (I );
Name = curnode. getnodename ();
Value = curnode. getnodevalue ();
System. Out. println ("/t" + name + "=" + value );
}
}
// Print the names and values of all nodes
// The method is used to print all nodes of the document recursively.
Public static void printelement (element ELEM, int depth ){
String elementname;
Nodelist children;
Int I, Max;
Node curchild;
Element curelement;
String nodename, nodevalue;
// Elementname = ELEM. getnodename ();
// Obtain all the subnodes of the input node
Children = ELEM. getchildnodes ();
// Print the input node in a certain format
For (Int J = 0; j <depth; j ++ ){
System. Out. Print ("");
}
Printattributes (ELEM );
// Print all child nodes recursively
Max = children. getlength ();
For (I = 0; I <Max; I ++ ){
Curchild = children. item (I );
// Recursive exit condition
If (curchild instanceof element ){
Curelement = (element) curchild;
Printelement (curelement, depth + 1 );
}
Else {
Nodename = curchild. getnodename ();
Nodevalue = curchild. getnodevalue ();
For (Int J = 0; j <depth; j ++) system. Out. Print ("");
System. Out. println (nodename + "=" + nodevalue );
}
}
}
}