Difference between revisions of "DOM Tutorial 2"

From Progzoo
Jump to: navigation, search
(Navigating Back and Forth)
(firstChild and lastChild)
 
Line 90: Line 90:
 
public class D
 
public class D
 
{
 
{
   public static void main(String[] args) {
+
   public static void main(String[] args)  
 
+
  {
     try {
+
     try
 +
    {
 
       DocumentBuilderFactory dbf =
 
       DocumentBuilderFactory dbf =
 
         DocumentBuilderFactory.newInstance();
 
         DocumentBuilderFactory.newInstance();
Line 101: Line 102:
 
       Element f = (Element)e.getChildNodes().item(1);
 
       Element f = (Element)e.getChildNodes().item(1);
 
       System.out.println(f.getAttribute("legend"));
 
       System.out.println(f.getAttribute("legend"));
     } catch (Exception ex) {
+
     }
 +
    catch (Exception ex)
 +
    {
 
       System.out.println(ex);
 
       System.out.println(ex);
 
     }
 
     }
Line 113: Line 116:
 
public class D
 
public class D
 
{
 
{
   public static void main(String[] args) {
+
   public static void main(String[] args)
 
+
  {
     try {
+
     try  
 +
    {
 
       DocumentBuilderFactory dbf =
 
       DocumentBuilderFactory dbf =
 
         DocumentBuilderFactory.newInstance();
 
         DocumentBuilderFactory.newInstance();
Line 126: Line 130:
 
       System.out.println(f.getAttribute("legend"));
 
       System.out.println(f.getAttribute("legend"));
 
       System.out.println(l.getAttribute("legend"));
 
       System.out.println(l.getAttribute("legend"));
     } catch (Exception ex) {
+
     }
 +
    catch (Exception ex)
 +
    {
 
       System.out.println(ex);  
 
       System.out.println(ex);  
 
     }
 
     }

Latest revision as of 20:51, 12 September 2012

You can navigate around your DOM document using methods such as:

getParentNode()
getChildNodes()
getFirstChild()
getLastChild()
getNextSibling()
getPreviousSibling()

Some of these are methods of Node some and methods of Element. Most return a Node however one returns an Element and one returns a NodeList. Can you figure out which? If not then look it up at http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/java-language-binding.html

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE stock [
<!ELEMENT stock (item*)>
<!ELEMENT item EMPTY>
<!ATTLIST item id ID #REQUIRED
               legend CDATA #REQUIRED
               price CDATA #REQUIRED>
]>
<stock>
  <item id="E1" price="50" legend="Pr-Burger" />
  <item id="E5" price="15" legend="Crisp S+V" />
  <item id="E6" price="15" legend="Crisp C+O" />
  <item id="E7" price="50" legend="Flat Cola" />
</stock>

Navigating Back and Forth

Print the legend of the element before "E6".


[Font] [Default] [Show] [Resize] [History] [Profile]

firstChild and lastChild

Print the legend of first child of the document element also the last child



[Font] [Default] [Show] [Resize] [History] [Profile]