W3C. Dom component XML parsing instance
Package com. Yanek. Demo. xml. test;
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Import java. util. hashmap;
Import java. util. Map;
Import org. W3C. Dom. Document;
Import org. W3C. Dom. element;
Import org. W3C. Dom. nodelist;
Import org. xml. Sax. inputsource;
Import org. xml. Sax. saxexception;
Import com.sun.org. Apache. xerces. Internal. parsers. domparser;
Public class domparserbean {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
/*************************************** ********************************
* <? XML version = "1.0" encoding = "UTF-8"?> <Actions> <action Path = "/test"
* Class = "com. mystruts. Demo. loginaction"> <forward name = "success"
* Url = "Hello. jsp"/> <forward name = "fail" url = "fail. jsp"/> </Action> <action
* Path = "/user" class = "com. mystruts. Demo. useraction"> <forward
* Name = "success" url = "list. jsp"/> <forward name = "fail" url = "fail. jsp"/> </Action> </actions>
*/
Try {
Document document = domparserbean. getdocument ("D: // mystruts. xml ");
Nodelist actions = Document. getelementsbytagname ("action ");
Int size = actions. getlength ();
Map result = new hashmap ();
For (INT I = 0; I <size; I ++ ){
Element xml_action = (element) actions. item (I );
System. Out. println ("class =" + xml_action.getattribute ("class "));
System. Out. println ("Path =" + xml_action.getattribute ("path "));
Nodelist xml_forwards = xml_action
. Getelementsbytagname ("Forward ");
For (Int J = 0; j <xml_forwards.getlength (); j ++ ){
Element forward = (element) xml_forwards.item (j );
System. Out. println (forward. getattribute ("name "));
System. Out. println (forward. getattribute ("url "));
}
}
} Catch (saxexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
Private domparserbean (){
} // Disallow instantiation
Public static document getdocument (string file) throws saxexception,
Ioexception {
Domparser parser = new domparser ();
Parser. parse (New inputsource (New fileinputstream (File )));
Return parser. getdocument ();
}
}
Output:
Class = com. mystruts. Demo. loginaction
Path =/test
Success
Hello. jsp
Fail
Fail. jsp
Class = com. mystruts. Demo. useraction
Path =/user
Success
List. jsp
Fail
Fail. jsp