package util;
import java.util.Vector;
import module.News;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXml {
Vector n = new Vector();
public Vector parseXml(Document d) {
Element rootElement = d.getDocumentElement();
rootElement.normalize();
displayNode(rootElement, 0);
return n;
}
private void displayNode(Node node, int depth) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
NodeList childNodes = node.getChildNodes();
int numChildren = childNodes.getLength();
if (node.getNodeName().equals("item")) {
NodeList child = node.getChildNodes();
int a = child.getLength();
String title = "";
String body = "";
String time = "";
for (int j = 0; j < a; j++) {
String s;
String tagname = null;
try {
tagname = child.item(j).getNodeName();
s = child.item(j).getFirstChild().getNodeValue();
} catch (Exception e) {
s = "";
}
if (tagname.equals("title")) {
title = s;
continue;
}
if (tagname.equals("description")) {
body = s;
continue;
}
if (tagname.equals("pubDate")) {
time = s;
continue;
}
}
News news = new News(title, time, body);
n.addElement(news);//保存到vector中
} else {
for (int i = 0; i < numChildren; ++i) {
displayNode(childNodes.item(i), depth + 1);
}
}
}
}
}
import java.util.Vector;
import module.News;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXml {
Vector n = new Vector();
public Vector parseXml(Document d) {
Element rootElement = d.getDocumentElement();
rootElement.normalize();
displayNode(rootElement, 0);
return n;
}
private void displayNode(Node node, int depth) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
NodeList childNodes = node.getChildNodes();
int numChildren = childNodes.getLength();
if (node.getNodeName().equals("item")) {
NodeList child = node.getChildNodes();
int a = child.getLength();
String title = "";
String body = "";
String time = "";
for (int j = 0; j < a; j++) {
String s;
String tagname = null;
try {
tagname = child.item(j).getNodeName();
s = child.item(j).getFirstChild().getNodeValue();
} catch (Exception e) {
s = "";
}
if (tagname.equals("title")) {
title = s;
continue;
}
if (tagname.equals("description")) {
body = s;
continue;
}
if (tagname.equals("pubDate")) {
time = s;
continue;
}
}
News news = new News(title, time, body);
n.addElement(news);//保存到vector中
} else {
for (int i = 0; i < numChildren; ++i) {
displayNode(childNodes.item(i), depth + 1);
}
}
}
}
}