1. Create a new XML document:
DocumentDoc= Documenthelper.
createdocument();Element root = Doc.addelement ("OCS");Root.addelement ("Header");Element BODY = root.addelement ("Body");Element Fontnode = body.addelement ("Font");Fontnode.addattribute ("Size", "9");System.
out. println (Root.asxml ()); 2. Open an existing XML document (import from a string): Document doc = Documenthelper.
ParseText(XMLSTR);node node = doc.selectsinglenode ( "Ocs/body/font");
if(Node
instanceofElement) {element pnode = (element) node; Attribute attr = Pnode.attribute ("Size");System.
out. println (Attr.asxml ()); } XPath is built into the dom4j, so you canAccess the path string as XPath in selectSingleNode, note that the Jaxen-1.1.1.jar package needs to be referenced, otherwise selectSingleNode will produce an exception and return null; 3. Open an existing document (import from file): Saxreader Saxreader =
NewSaxreader ();Document document = Saxreader.read ( xmlfile); 4. Write the document to the file:
Try {XMLWriter output =
NewXMLWriter (
NewFileWriter (
NewFile (xmlfile ));Output.write (DOC);output.close (); }
Catch(IOException e) {System.
out. println (E.getmessage ()); }
Java dom4j XML Usage Summary