Difference between revisions of "DOM Tutorial 2"

From Progzoo
Jump to: navigation, search
(Navigating Back and Forth)
Line 32: Line 32:
 
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 43: Line 44:
 
       e = (Element)e.getNextSibling();
 
       e = (Element)e.getNextSibling();
 
       System.out.println(e.getAttribute("legend"));
 
       System.out.println(e.getAttribute("legend"));
     } catch (Exception ex) {
+
     }
 +
    catch (Exception ex)
 +
    {
 
       System.out.println(ex);
 
       System.out.println(ex);
 
     }
 
     }
Line 55: Line 58:
 
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 66: Line 70:
 
       e = (Element)e.getPreviousSibling();
 
       e = (Element)e.getPreviousSibling();
 
       System.out.println(e.getAttribute("legend"));
 
       System.out.println(e.getAttribute("legend"));
     } catch (Exception ex) {
+
     }
 +
    catch (Exception ex)
 +
    {
 
       System.out.println(ex);
 
       System.out.println(ex);
 
     }
 
     }

Revision as of 20:50, 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]