DOM4J Study Notes

Source: Internet
Author: User

One, Loading XML Data

The following code reads an XML file from file or a URL and produces a document object. A Document object represents an XML tree in memory that can be traversed, queried, modified, and manipulated in this XML tree.

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
}
}

ii. QName and Namespace

The QName object represents the qualified name of an XML element or attribute, which is a two-tuple of one namespace and one local name.

The Namespace object represents the namespace part of the QName two tuple, which consists of the prefix and the URI two parts.

/******************** SAMPLE XML FILE *************************
xmlns:heavyz= "Http://www.heavyzheng.com/schema/sample.xsd" >
*************************************************************/

public void Printrootqnameinfo (Document doc) {
Element root = Doc.getrootelement ();
QName QName = Root.getqname ();
System.out.println ("Local name:" + qname.getname ());
System.out.println ("namespace prefix:" + qname.getnamespaceprefix ());
System.out.println ("namespace URI:" + Qname.getnamespaceuri ());
SYSTEM.OUT.PRINTLN ("Qualified name:" + qname.getqualifiedname ());
Return
}

/************************* OUTPUT *****************************
Localname:sample
Namespace Prefix:heavyz
Namespace Uri:http://www.heavyzheng.com/schema/sample.xsd
Qualified Name:heavyz:Sample
*************************************************************/

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

You can call the QName (string name) construction method to construct a qualified name without Namespace, or call QName (string name, Namespace Namespace) Construction method constructs a namespace qualified name.

Third, Navigating Through an XML Tree

calling the getrootelement () method on the Document object returns the Element object that represents the root node . once you have an element object, you can call the Elementiterator () method on the object to get a iterator of the element object for its child nodes . Use the (Element) Iterator.next () method to traverse a iterator and convert each of the extracted elements into the element type.

The following code can print out the complete XML tree based on the document object by means of a recursive method.

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
}
Iv. Getting Information from an Element

The information contained in an XML element can be accessed through the methods provided by the element class:

Method Comment
Getqname () The QName object of the element
GetNamespace () The Namespace object to which the element belongs
Getnamespaceprefix () The 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 () The qualified name of the element
GetText () The text content contained in the element, and returns an empty string instead of null if the content is empty
Gettexttrim () The text content contained in the element, where consecutive spaces are converted to a single space, and the method does not return null
Attributeiterator () The iterator of the element property, where each element is a attribute object
AttributeValue () The value contained in a specified property of an element
Elementiterator () The iterator of the element's child elements, each of which is an element object
Element () A child element of a specified (qualified name or local name) of an element
Elementtext () The text information in a child element of a specified (qualified name or local name) element
GetParent The parent element of the element
GetPath () An XPath expression for the element, where the parent element's qualified name and child element's qualified name are separated by "/"
Istextonly () Whether the element contains only text or empty elements
Isrootelement () Whether the element is the root node of the XML tree

To remove information about a property in an element object, you can call the Attributeiterator () method to get the iterator of a attribute object and then traverse it. You can also call the AttributeValue () method directly to get the value of the specified property. The method accepts four types of parameters:

    • AttributeValue (QName QName): Gets the property value by specifying the qualified name and returns NULL if the specified property cannot be found .
    • AttributeValue (QName QName, String defaultvalue): Gets the property value by specifying the qualified name, and returns defaultvalue if the specified property cannot be found .
    • AttributeValue (String name): Returns the property value by specifying the local name, ignoring the property's namespace, or null if the specified property cannot be found .
    • AttributeValue (string name, String defaultvalue): Gets the property value by specifying the local name, ignoring the namespace of the property, and returns if the specified property cannot be found. DefaultValue.

For a attribute object, you can use it to access information in the following ways:

Method Comment
Getqname () The QName object of the property
GetNamespace () The Namespace object to which the property belongs
Getnamespaceprefix () The prefix of the namespace object to which the property belongs
Getnamespaceuri () The URI of the namespace object to which the property belongs
GetName () The local name of the property
Getqualifiedname () Qualified name of the property
GetValue () The value of the property
v. Writing an XML Tree to OutputStream

dom4j writes the XML tree represented by the Document object to a file by XmlWriter, and uses the OutputFormat format object to specify the style and encoding method of the write. Call the Outputformat.createprettyprint () method to get a default pretty print-style format object. You can specify an encoding method for an XML file by calling the Setencoding () method on the OutputFormat object.

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
}
VI, Creating an XML Tree

creates 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 creates the XML root node and returns 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;
}
}
vii. Adding information into an Element

Element adds a child node to the back of all current child nodes by AddElement (). The method can accept three different types of parameters:(QName QName),(string name), or (string qualifiedname, String NamespaceURI). The method returns an element object that adds a child node .

Element adds properties to itself through AddAttribute (). The method can accept two different types of arguments:(QName QName, String value) or (string name, String value). The method returns its own element object.

Element adds text content to itself through AddText (). The method accepts only the string type argument 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
}
viii. Deleting Elements and Attributes

To delete a subtrees tree on an XML tree, first find the root node of the subtree, and then call the Detach () method on that node. Note: If the detach () method is called on the root node , it will cause the XML tree to be no longer complete (an XML file needs to have only one root node).

public void Deletesubtree (Element subtreeroot) {
Subtreeroot.detach ();
Return
}

To clear all child nodes (including element and text) under element, you can call the clearcontent () method on the element. This method does not clear the properties of element.

To clear a Attribute under element , first obtain the Attribute object and then call it as a parameter to the remove () method of element.

IX, Updating an Attribute

To update the contents of a property, you first get the attribute object, and then you can call the Setnamespace () method to update the namespace it belongs to, and call the SetValue () method to update its property values.

10, Updating an Element ' s Text

You can call the Istextonly () method on an Element object to determine whether it contains only text or NULL nodes. calling the AddText () method on the Element object appends a string to the element, but does not modify the text or child nodes it originally owned. If element is istextonly (), to modify the original text, you can call clearcontent (), call AddText (), and pass in the new value.

public void UpdateText (element element, String NewText) {
if (Element.istextonly ()) {
Element.clearcontent ();
Element.addtext (NewText);
}
Return
}

DOM4J Study Notes

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.