!! Dom4j Study Notes

Source: Internet
Author: User
Tags print format

The following code reads an XML file from a file or URL and generates a Document Object. A document object represents an XML tree in the memory, which allows you to traverse, query, modify, and perform other operations.

import java.io.*;import java.net.*;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;public class XMLLoader {        private Document doc = null;        public void parseWithSAX(File file)    throws MalformedURLException, DocumentException {        SAXReader xmlReader = new SAXReader();        this.doc = xmlReader.read(file);        return;    }        public void parseWithSAX(URL url)    throws MalformedURLException, DocumentException {        SAXReader xmlReader = new SAXReader();        this.doc = xmlReader.read(url);        return;    }}        

QNAME and namespace

The QNAME object represents the qualified name of an XML element or attribute, that is, a namespace and a binary group of a local name.

The namespace object represents the namespace part in the QNAME Binary Group. It consists of prefix and Uri.

/******************** SAMPLE XML FILE *************************  

You can call the namespace (string prefix, string URI) constructor to construct a new namespace object, or call namespace. get (string prefix, string URI) static method to obtain a new namespace object.

You can call the QNAME (string name) constructor to construct a qualified name without namespace, or call the QNAME (string name, namespace) constructor to construct a qualified name with namespace.

Navigating through an XML tree

Call the getrootelement () method on the document object to return the element object representing the root node. If you have an element object, you can call the elementiterator () method to obtain an iterator of the element object of its subnodes. Use the (element) iterator. Next () method to traverse an iterator and convert each retrieved element to the element type.

The following code uses recursion to print the complete XML tree based on the document object.

public void printXMLTree(Document doc) {    Element root = doc.getRootElement();    printElement(root,0);    return;}    private void printElement(Element element, int level) {    // print indent    for (int i=0; i<level; i++) {        System.out.print(" ");    }    System.out.println(element.getQualifiedName());    Iterator iter = element.elementIterator();    while (iter.hasNext()) {        Element sub = (Element)iter.next();        printElement(sub,level+2);    }    return;}        

Getting information from an element

You can access the information contained in an XML element through the methods provided by the element class:

Method Comment
Getqname () Element QNAME object
Getnamespace () Namespace object to which the element belongs
Getnamespaceprefix () Prefix of the namespace object to which the element belongs
Getnamespaceuri () The URI Of The namespace object to which the element belongs.
Getname () The local name of the element.
Getqualifiedname () Qualified name of the element
Gettext () The text content contained in the element. if the content is null, an empty string instead of null is returned.
Gettexttrim () The text content contained in the element. Consecutive spaces are converted to a single space. This method does not return null.
Attributeiterator () Iterator of element attributes, where each element is an attribute object
Attributevalue () The value of a specified attribute of an element.
Elementiterator () The iterator of the child element of the element. Each element is an element object.
Element () A child element of a specified Element (qualified name or local name)
Elementtext () Text Information in a child element of an element specified (qualified name or local name)
Getparent Element parent Element
Getpath () Element. The qualified name of the parent element and the qualified name of the child element are separated "/".
Istextonly () Whether the element only contains text or empty elements
Isrootelement () Whether the element is the root node of the XML tree

To retrieve information about an attribute in an element object, you can call attributeiterator () to obtain the iterator of an attribute object and traverse it. You can also directly call attributevalue () to obtain the value of the specified attribute. This method accepts four types of parameters:

  • Attributevalue (QNAME): obtains the attribute value by specifying the qualified name. If the specified attribute cannot be found, null is returned.
  • Attributevalue (QNAME, string defaultvalue): obtains the attribute value by specifying the qualified name. If the specified attribute cannot be found, defavalue value is returned.
  • Attributevalue (string name): obtains the attribute value by specifying the local name, while ignoring the namespace of the attribute. If the specified attribute cannot be found, null is returned.
  • Attributevalue (string name, string defaultvalue): obtains the attribute value by specifying the local name, and ignores the namespace of the attribute. If the specified attribute cannot be found, defavalue value is returned.

An Attribute object can be accessed using the following methods:

Method Comment
Getqname () Attribute QNAME object
Getnamespace () Namespace object to which the property belongs
Getnamespaceprefix () Prefix of the namespace object to which the property belongs
Getnamespaceuri () The URI Of The namespace object to which the property belongs.
Getname () Local name of the property
Getqualifiedname () Qualified name of the attribute
Getvalue () Attribute Value

Writing an XML tree to outputstream

Dom4j writes the XML Tree represented by the document object to a file through xmlwriter, and uses the outputformat format object to specify the writing style and encoding method. Call outputformat. createprettyprint () to obtain a default pretty print format object. You can call the setencoding () method on the outputformat object to specify the encoding method of the XML file.

public void writeTo(OutputStream out, String encoding)throws UnsupportedEncodingException, IOException {    OutputFormat format = OutputFormat.createPrettyPrint();    format.setEncoding("gb2312");    XMLWriter writer = new XMLWriter(System.out,format);    writer.write(doc);    writer.flush();    return;}        

Creating an XML tree

Create an empty Document Object using the documentfactory object. The documentfactory object is generated by the documentfactory. getinstance () static method. Calling the addelement () method on the document object will create an XML root node and return the node. You can also manually create an element object and call the document. setrootelement () method to set it as the root node.

import org.dom4j.DocumentFactory;import org.dom4j.Document;import org.dom4j.Element;public class XMLSaver {        private DocumentFactory factory = null;    private Document doc = null;    private Element root = null;        public XMLSaver() {        factory = DocumentFactory.getInstance();        doc = factory.createDocument();    }        public Element generateRoot(String name) {        root = doc.addElement(name);        return root;    }        public Element generateRoot(QName qname) {        root = doc.addElement(qname);        return root;    }        public Element generateRoot(Element element) {        doc.setRootElement(element);        root = element;        return root;    }}        

Adding information into an element

Element adds a subnode to the end of all subnodes through addelement. This method can accept three different types of parameters: (QNAME), (string name), or (string qualifiedname, string namespaceuri ). This method returns the Element Object of the added subnode.

Element adds attributes for itself through addattribute. This method can take two different types of parameters: (QNAME, string value) or (string name, string value ). This method returns its own element object.

Element adds text content to itself through addtext. This method only accepts string type parameters and returns its own element object.

public void addAuthors(Element bookElement) {    Element author1 = bookElement.addElement("author");    author1.addAttribute("name","Toby");    author1.addAttribute("location","Germany");    author1.addText("Tobias Rademacher");    Element author2 = bookElement.addElement("author");    author2.addAttribute("name","James");    author2.addAttribute("name","UK");    author2.addText("James Strachan");        return;}        

Deleting elements and attributes

To delete a subtree in the XML tree, first locate the root node of the subtree and call the detach () method on the node. Note: If the detach () method is called for the root node, the XML tree will not be complete (an XML file must have only one root node ).

public void deleteSubtree(Element subtreeRoot) {    subtreeRoot.detach();    return;}        

To clear all subnodes (including elements and text) under an element, you can call the clearcontent () method on this element. This method does not clear the attributes of the element.

To clear an attribute under an element, first obtain the attribute object and call the remove () method of element as a parameter.

Updating an attribute

To update the content of an attribute, first obtain the attribute object, and then call the setnamespace () method to update its namespace. Call the setvalue () method to update its attribute value.

Updating an element's text

You can call the istextonly () method on an element object to determine whether it only contains text or empty nodes. Calling the addtext () method for the element object will append a string to the element, but it will not modify its original text or subnode. If the element is istextonly (), you can call clearcontent () first, then addtext (), and pass in the new value.

public void updateText(Element element, String newText) {    if (element.isTextOnly()) {        element.clearContent();        element.addText(newText);    }    return;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.