Java examples for XML:XML Attribute
Traverses the given DOM, relative to all the URIs in the uri attributes of each Element.
//package com.java2s; import org.w3c.dom.*; import java.net.URI; public class Main { /**//from ww w . java 2 s .c om * Traverses the given DOM, relativising all the URIs in the * <code>uri</code> attributes of each <code>Element</code>. * * <p>The (uri-attribute) nodes in the input DOM are modified by this * method; if this is a problem, use {@link * org.w3c.dom.Node#cloneNode} first. * * @param n a node containing the DOM whose URIs are to be * relativized. If this is null, the method immediately returns null * @param baseURI the URI relative to which the DOM is to be * relativised. If this is null, then the input node is * immediately returned unchanged. * @param attname the attribute name to be used. If null, this * defaults to <code>uri</code> * @return the input node * @see java.net.URI#relativize */ public static Node relativizeDOM(Node n, URI baseURI, String attname) { if (n == null || baseURI == null) return n; if (attname == null) attname = "uri"; NamedNodeMap nm = n.getAttributes(); if (nm != null) for (int i = 0; i < nm.getLength(); i++) { Attr att = (Attr) nm.item(i); if (att.getName().equals(attname)) { String oldAttValue = att.getValue(); try { att.setValue(baseURI.relativize( new URI(oldAttValue)).toString()); } catch (java.net.URISyntaxException ex) { // Malformed URI -- restore the attribute to its original value att.setValue(oldAttValue); } } } for (Node kid = n.getFirstChild(); kid != null; kid = kid .getNextSibling()) relativizeDOM(kid, baseURI, attname); return n; } }