Java Dom4j XML usage summary, javadom4jxml usage
1. Create an XML document:
Document doc = incluenthelper.
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 the existing XML Document (import from 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 ();} Dom4j has built-in XPath, so you can access the path string in selectSingleNode as in XPath; Note: You need to reference the jaxen-1.1.1.jar package, otherwise selectSingleNode will produce an exception and return Null; 3. Open an existing document (import from a 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 ());}