Import JDOM. Jar. JDOM provides easy-to-use methods for reading and writing XML files.
1. Write XML
Example:
Import org. JDOM. Document;
Import org. JDOM. element;
Import org. JDOM. Output. xmloutputter;
PublicClassXmlwriter {
PrivateElement wroot =Null;
PrivateDocument wdoc =Null;
PublicVoidInitwroot (){
Try{
Wroot =NewElement ("Database ");
Wdoc =NewDocument (wroot );
}
Catch(Exception e ){
E. printstacktrace ();
}
}
PublicVoidWritexml (string strfilename ){
Try{
File F =NewFile (strfilename );
If(F. exists ()){
F. Delete ();
}
F. createnewfile ();
Xmloutputter xmlout =NewXmloutputter ();
Xmlout. Output (wdoc,NewFileoutputstream (strfilename ));
}
Catch(Exception e ){
E. printstacktrace ();
}
}
}
Add nodes in XML:
Public element addnode (element ecur, string nodename ){
Element echild =Null;
Try{
Echild =NewElement (nodename );
Ecur. addcontent (echild );
}
Catch(Exception e ){
E. printstacktrace ();
}
ReturnEchild;
}
The preceding method is used to obtain the wdoc document object and its root node wroot. The addnode () method can be called to insert a subnode into the root node, and the returned subnode object echild is the same, you can insert subnodes at the next level into the child node echild. Finally, call the writexml () method to save it as an XML file.
Ii. Read XML
Import org. JDOM. Document;
Import org. JDOM. element;
Import org. JDOM. jdomexception;
Import org. JDOM. Input. saxbuilder;
PublicClassXmlreader {
Private element rroot =Null;
PublicVoidInitrroot (string strxmlpathfile)ThrowsIoexception, jdomexception {
Saxbuilder =NewSaxbuilder ();
Document read_doc = builder. Build (strxmlpathfile );
Rroot = read_doc.getrootelement ();
}
}
Use the above Code to obtain the root node rroot of the XML file. Next, you can call the rroot list <element> getchildren (string nodename) method to obtain its subnodes. Similarly, you can traverse the getchilren () methods of each subnode in sequence. You can obtain the node attribute values through the string getattributevalue (string attrname) of the element.