/* * @(#)TransformationApp02b.java 1.9 98/11/10 */ //for DOMEcho01 part import java.io.File; import java.io.IOException; import java.io.*; import java.io.FilterOutputStream; //----- import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.w3c.dom.Document; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Attr; import org.w3c.dom.NodeList; // For write operation import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; public class TransformationApp02b { // Global value so it can be ref'd by the tree-adapter static Document document; static Node temp, temp2, brother; static String myString; public static void main (String argv []) { if (argv.length != 1) { System.err.println ("Usage: java TransformationApp02a filename"); System.exit (1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //factory.setNamespaceAware(true); factory.setValidating(true); try { File f = new File(argv[0]); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(f); //----------------- Node root =document.getDocumentElement(); if(root==null) System.out.println("getDocumentElement returned NULL"); else System.out.println( root.getNodeName() ); //System.exit(0); // Node root = findSubNode("slideShow", document.getDocumentElement()); /*1*/ root.appendChild( document.createTextNode("Some text.\n ") ); /*2*/ Element workingElement = document.createElement("MyFirstXMLtag"); root.appendChild( workingElement ); workingElement.appendChild(document.createTextNode("Some Content "));// /*3*/ Element workingElement2 = document.createElement("MyXMLtag"); root.appendChild( workingElement2 ); workingElement2.appendChild(document.createTextNode("Some other Content ")); Attr attribute = document.createAttribute("title"); workingElement2.setAttributeNode(attribute); attribute.setNodeValue("Nachum's favorite title"); /*4*/ Element workingElement3 = document.createElement("MyXMLtag"); root.appendChild( workingElement3 ); workingElement3.appendChild(document.createTextNode("Some New other Content ")); attribute = document.createAttribute("title"); workingElement3.setAttributeNode(attribute); attribute.setNodeValue("Nachum's favorite title"); Element subelement = document.createElement("MySubElement"); workingElement3.appendChild( subelement ); subelement.appendChild(document.createTextNode("Some Sub Content ")); /*5*/ //replaceChild Element replacementElement = document.createElement("MySecondXMLtag"); replacementElement.appendChild(document.createTextNode("Some Replacement Content ")); temp = findSubNode("MyFirstXMLtag",root ) ; //root.replaceChild(Node newChild, Node oldChild) root.replaceChild(replacementElement, temp); /*6*/ // alternate replaceChild Element replacementElement2 = document.createElement("MyThirdXMLtag"); replacementElement2.appendChild(document.createTextNode("Some New Replacement Content ")); brother=root.getFirstChild(); if (brother == null){ System.err.println("is not the first child "); } temp2 = findSiblingNode("MySecondXMLtag",brother) ; //root.replaceChild(Node newChild, Node oldChild) if (temp2 != null){ root.replaceChild(replacementElement2, temp2); } /*7*/ //removeChild example workingElement3.removeChild(subelement); /*8*/ // get all node texts myString = new String(); Node a = findSubNode("slide",root ); /// find the first slide Node b = findSubNode("title",a ); // find its title myString = getText(b ); //get the title's text System.out.println(myString); //------------------ // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); //THIS LINE IS NEEDED TO CREATE A REFERENCE TO THE DTD IN YOUR XML PAGE // transformer.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM,"My.dtd"); DOMSource source = new DOMSource(document); File file = new File("stam.stam"); StreamResult result = new StreamResult(file); //StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println ("\n** Transformer Factory error"); System.out.println(" " + tce.getMessage() ); // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } catch (TransformerException te) { // Error generated by the parser System.out.println ("\n** Transformation error"); System.out.println(" " + te.getMessage() ); // Use the contained exception, if any Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); } catch (SAXParseException spe) { // Error generated by the parser System.out.println("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); } catch (SAXException sxe) { // Error generated by this application // (or a parser-initialization error) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } } // main static public Node findSubNode(String name, Node node) { if (node.getNodeType() != Node.ELEMENT_NODE) { System.err.println("Error: Search node not of element type"); System.exit(22); } if (! node.hasChildNodes()) return null; NodeList list = node.getChildNodes(); for (int i=0; i < list.getLength(); i++) { Node subnode = list.item(i); if (subnode.getNodeType() == Node.ELEMENT_NODE) { System.out.println(subnode.getNodeName()); if (subnode.getNodeName() == name) return subnode; } } return null; } static public Node findSiblingNode(String name, Node node) { Node sibling = node; for (; ;) { if (sibling == null) { System.out.println("No more siblings left."); return null; } if (sibling.getNodeType() == Node.ELEMENT_NODE) //this is an Element { System.out.println(sibling.getNodeName()); if (sibling.getNodeName() == name) return sibling; } sibling=sibling.getNextSibling(); }//end for } /* recursive version of findSiblingNode static public Node findSiblingNode(String name, Node node) { if (node == null) //base case { System.out.println("No more nodes left."); return null; } if (node.getNodeType() == Node.ELEMENT_NODE) //this is an Element { if (node.getNodeName() == name) return sibling; } findSiblingNode(name, node.getNextSibling()); } */ static public String getText(Node node) { StringBuffer result = new StringBuffer(); if (! node.hasChildNodes()) return ""; NodeList list = node.getChildNodes(); for (int i=0; i < list.getLength(); i++) { Node subnode = list.item(i); if (subnode.getNodeType() == Node.TEXT_NODE) { result.append(subnode.getNodeValue()); } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { result.append(subnode.getNodeValue()); } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { // Recurse into the subtree for text // (and ignore comments) result.append(getText(subnode)); } } return result.toString(); } }