|
NOTE:
These slides have not been updated since 2003. They have been superseded by the book
Anders Møller and Michael Schwartzbach, February 2006 |
|
| THE XML REVOLUTION - TECHNOLOGIES FOR THE FUTURE WEB |
|
import java.io.*;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.*;
public class FirstRecipeDOM {
public static void main(String[] args) {
try {
DOMParser p = new DOMParser();
p.parse(args[0]);
Document doc = p.getDocument();
Node n = doc.getDocumentElement().getFirstChild();
while (n!=null && !n.getNodeName().equals("recipe"))
n = n.getNextSibling();
PrintStream out = System.out;
out.println("<?xml version=\"1.0\"?>");
out.println("<collection>");
if (n!=null)
print(n, out);
out.println("</collection>");
} catch (Exception e) {e.printStackTrace();}
}
static void print(Node node, PrintStream out) {
int type = node.getNodeType();
switch (type) {
case Node.ELEMENT_NODE:
out.print("<" + node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
int len = attrs.getLength();
for (int i=0; i<len; i++) {
Attr attr = (Attr)attrs.item(i);
out.print(" " + attr.getNodeName() + "=\"" +
escapeXML(attr.getNodeValue()) + "\"");
}
out.print('>');
NodeList children = node.getChildNodes();
len = children.getLength();
for (int i=0; i<len; i++)
print(children.item(i), out);
out.print("</" + node.getNodeName() + ">");
break;
case Node.ENTITY_REFERENCE_NODE:
out.print("&" + node.getNodeName() + ";");
break;
case Node.CDATA_SECTION_NODE:
out.print("<![CDATA[" + node.getNodeValue() + "]]>");
break;
case Node.TEXT_NODE:
out.print(escapeXML(node.getNodeValue()));
break;
case Node.PROCESSING_INSTRUCTION_NODE:
out.print("<?" + node.getNodeName());
String data = node.getNodeValue();
if (data!=null && data.length()>0)
out.print(" " + data);
out.println("?>");
break;
}
}
static String escapeXML(String s) {
StringBuffer str = new StringBuffer();
int len = (s != null) ? s.length() : 0;
for (int i=0; i<len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '<': str.append("<"); break;
case '>': str.append(">"); break;
case '&': str.append("&"); break;
case '"': str.append("""); break;
case '\'': str.append("'"); break;
default: str.append(ch);
}
}
return str.toString();
}
}
|
Note that:
|
| COPYRIGHT © 2000-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH |
|