200 likes | 380 Vues
Manipulating DOM Tree. Objectives. Nodes API to seek Items in XML Document API to modify an XML Document. Workshops. Node. Document Represents the entire DOM document. Is the root node of the XML document. This acts as the gate way for accessing the document and processing it.
E N D
Objectives Nodes API to seek Items in XML Document API to modify an XML Document. Workshops
Node • Document • Represents the entire DOM document. • Is the root node of the XML document. This acts as the gate way for accessing the document and processing it. • Document Fragment • Holds a portion of a complete document. • Is created by the methods present in the Document interface. • Can have processing instruction, comment, text, CDATA section, and entity reference as its child nodes. • Document Type • Each document has a DOCTYPE attribute. It can have value as null or an object of the DocumentType interface. • Is created by the Document interface. • Provides an interface to the entities defined for the document. • Processing Instruction • This is just a processor specific instruction kept in the XML document. • The Document interface creates a Processing Instruction node.
Types of Nodes • Entity • Converts a relative lengthy textual content to a short notation. • The Document interface creates an Entity node. • There are three types of entities internal entity, external entity, and parameter entity. • Entity Reference • Acts as a reference to the predefined entity. • The Document interface creates an entity reference node. • Can have element, processing instruction, comment, text, CDATA section and entity reference as its child nodes. • Element • Represents an element in a DOM tree. • The Node interface creates an Element node. • This type of node can contain attribute, other elements, or text. An element node containing an attribute is called as Attribute node. • Attribute • Represents the property of an element. • The Element interface creates an Attribute type node.
Types of Nodes (cont) • Text • Represents the textual content or value of an element or attribute. • The Element interface creates text node. • Has no child node of its own. • CDATA Section • The text inside this node is not subjected to parsing. The parser does not consider the tags inside this section as mark-up. • Has no child node. • Comment • Holds some comment lines for documentation purpose. • The Document interface creates a Comment node. • Has no child node of its own. • Notation • For example, to include a GIF image in your XML document, you will use the following notation: <!NOTATION GIF system “image/gif”>
Creating an Element Node public Element createElement(String tagName) throws DOMException Creating an Attribute Node public Attr createAttribute(String Name) throws DOMException Creating a Text Node public Text createTextNode(String data) Creating a CDATA Section Node public CDATASection createCDATASection(String data) throws DOMException Creating a Comment Node public Comment createComment(String data) Creating Nodes
public class DOMCreator { public static void main (String[] args) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = dbf.newDocumentBuilder (); Document doc = db.newDocument (); Element root = doc.createElement ("tomcat-users"); doc.appendChild (root); Comment comment = doc.createComment ("tomcat configuring file"); root.appendChild (comment); Element role = doc.createElement ("role"); role.setAttribute ("rolename", "tomcat"); root.appendChild (role); do it again with role role1, admin, manage Element user = doc.createElement ("user"); user.setAttribute ("username", "tomcat"); user.setAttribute ("password", "tomcat"); user.setAttribute ("roles", "tomcat"); root.appendChild (user); do it again with user role1, tomcat with tomcat, role1; admin, “” with admin, manger TransformerFactory transform = TransformerFactory.newInstance (); Transformer trans = transform.newTransformer (); trans.setOutputProperty (OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty (OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult rs = new StreamResult(sw); DOMSource dom = new DOMSource(doc); trans.transform (dom, rs); String str = sw.toString (); System.out.println("Tomcat - xml file \n\n" + str); } catch(Exception e){e.printStackTrace ();}}} Example
Appending Nodes • Add a Node to the End of a Node List public Node appendChild(Node newChild) throws DOMException • Insert a Node Before a specific Node public Node insertBefore(Node newChild, Node refChild) throws DOMException • Set a New Attribute and Attribute Value public void setAttribute(String name, String value) throws DOMException • Insert Data Into a Text Node public void insertData(int offset, String arg) throws DOMException
Locating document & Seeking attributes • The documentURI property • Syntax: documentObject.documentURI • Seeking an attributes • It is absolutely necessary to obtain an instance of the Attribute node to modify it. Through this object, attributes through out the tree can be searched for and accessed. For this, the Element interface defines some useful methods
Example public class SeekUser { public static void main (String[] args) { try { File f = new File("tomcat-users.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = dbf.newDocumentBuilder (); Document doc = db.parse (f); searchUser(doc); } catch(Exception e){e.printStackTrace ();} } private static void searchUser(Node node){ if(node==null){return;} if(node.getNodeName ().equals ("user")){ String str = node.getAttributes ().getNamedItem ("username").getNodeValue (); if(str.equals (“admin”)){ String pass = node.getAttributes ().getNamedItem ("password").getNodeValue (); System.out.println("USer " + str + "- password: " + pass); return;} } NodeList children = node.getChildNodes (); int i =0 ; while(i<children.getLength ()){ searchUser (children.item (i++));}}}
Modifying an Attribute • The Element interface provides several methods to modify the attributes and their values of an Element object in a DOM tree. • The modification of the attribute can be. • Creating a new attribute • Setting a new value to the attribute
Example public class UpdatePassword { static File f = null; public static void main (String[] args) { try {name = args[1]; f = new File("tomcat-users.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = dbf.newDocumentBuilder (); Document doc = db.parse (f); searchAndModify(doc); writeXML(doc); } catch(Exception e){e.printStackTrace ();}} private static void searchAndModify(Node node){ if(node==null){return;} if(node.getNodeName ().equals ("user")){ String str = node.getAttributes ().getNamedItem ("username").getNodeValue (); if(str.equals (“admin”)){ node.getAttributes ().getNamedItem ("password").setNodeValue (“aptech”); return;}} NodeList children = node.getChildNodes (); int i =0 ; while(i<children.getLength ()){searchAndModify (children.item (i++));}} private static void writeXML(Document doc) { try{Source source = new DOMSource(doc); Result result = new StreamResult(f); Transformer trans = TransformerFactory.newInstance ().newTransformer (); trans.transform (source, result); }catch(Exception e){e.printStackTrace ();}}}
WORKSHOP ACTIVITIES • Building the console Java application using DOM parser can do • Create the tomcat-user.xml document, then output the screen • Seeking the node in DOM document from tomcat-users.xml file after parsing • Update the password of the node in document from tomcat-users.xml file