Changing a namespace in XML using DOM4J

Hi All,

In this article I will show how to change XML Namespace.

Just a brief introduction about Namespace.

XML namespaces are used for providing uniquely named elements and attributes in an XML document. They are defined in Namespaces in XML, a W3C  recommendation. An XML instance may contain element or attribute names from more than one XML vocabulary. If each vocabulary is given a namespace then the ambiguity between identically named elements or attributes can be resolved.

A simple example would be to consider an XML instance that contained references to a customer and an ordered product. Both the customer element and the product element could have a child element named id. References to the id element would therefore be ambiguous; placing them in different namespaces would remove the ambiguity
//Example using DOM4J. Please download the DOM4J Jar and place in your project’s Lib folder.
// For detailed DOM4J article, Please click here.

import java.util.ListIterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;

public class
VisitorExample {

public static void main(String[] args) throws Exception {
//Read the XML File
Document doc = new SAXReader().read("test.xml");

// Now reterieve the old Namespace
Namespace oldNs = Namespace.get("oldNamespace");

//Add the new name space with new prefix
Namespace newNs = Namespace.get("newPrefix", "newNamespace");

// In DOM4J Navigation uses a Visitor pattern to travserse through the documnet,
// the same we will use to chnage the name sapce


Visitor visitor =
new NamesapceChangingVisitor(oldNs, newNs);
doc.accept(visitor);
System.out.println(doc.asXML());
}
}

class NamesapceChangingVisitor extends VisitorSupport {
private Namespace from;
private Namespace to;

public NamesapceChangingVisitor(Namespace from, Namespace to) {
this.from = from;
this.to = to;
}

public void visit(Element node) {

Namespace ns = node.getNamespace();

if (ns.getURI().equals(from.getURI())) {
QName newQName = new QName(node.getName(), to);
node.setQName(newQName);
}

ListIterator namespaces = node.additionalNamespaces().listIterator();
while (namespaces.hasNext()) {
Namespace additionalNamespace = (Namespace) namespaces.next();
if (additionalNamespace.getURI().equals(from.getURI())) {
namespaces.remove();
}
}
}

}

Hope this helps.

--
Thanks
R Vashi

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s