/* * (C) Copyright IBM Corp. 2004. All rights reserved. * * US Government Users Restricted Rights Use, duplication or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. * * The program is provided "as is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * IBM will not be liable for any damages suffered by you as a result * of using the Program. In no event will IBM be liable for any * special, indirect or consequential damages or lost profits even if * IBM has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ import com.ibm.dw.xmlprogjava.DomTreePrinter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Element; /** * A sample DOM application. This application reads an XML document, * builds a DOM tree, adds an attribute to each element in the DOM * tree, then prints the DOM tree. */ public class DomAttributes { public void parseAndProcessAttributes(String uri) { Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(uri); if (doc != null) { addAttributes(doc); DomTreePrinter.printNode(doc); } } catch (Exception e) { System.err.println("Sorry, an error occurred: " + e); } } public void addAttributes(Node node) { int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { addAttributes(((Document)node).getDocumentElement()); break; } case Node.ELEMENT_NODE: { Element el = (Element)node; el.setAttribute("size", "12"); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) addAttributes(children.item(i)); } break; } } } /** Main program entry point. */ public static void main(String argv[]) { if (argv.length == 0 || (argv.length == 1 && argv[0].equals("-help"))) { System.out.println("\nUsage: java DomAttributes uri"); System.out.println(" where uri is the URI of the XML " + "document you want to sort."); System.out.println(" Sample: java DomAttributes sonnet.xml"); System.out.println("\nAdds an attribute to all of the elements " + "in the DOM tree, then writes the DOm tree " + "to the console."); System.exit(1); } DomAttributes da = new DomAttributes(); da.parseAndProcessAttributes(argv[0]); } }