import org.jdom.input.*;
import org.jdom.Attribute;
import org.jdom.Element;
import org.xml.sax.SAXException;
import java.io.*;
import java.util.List;
import org.apache.xerces.parsers.*;
public class JDomDOM {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DOMBuilder builder = new DOMBuilder();
DOMParser parser = new DOMParser();
String path = "D:\\student.xml";
String output = "";
try {
parser.parse(path);
org.w3c.dom.Document domDocument = parser.getDocument();
org.jdom.Document jdomDocument = builder.build(domDocument);
Element root = jdomDocument.getRootElement();
output += "This XML document's root node is: " + root.getName() + "\r\n";
List <Element> children = root.getChildren();
output += "The root has " + children.size() + " subNodes \r\n";
for(int i = 0; i < children.size(); i++){
Element node = children.get(i);
output += "In the " + i + 1 + node.getName() + "subNode: \r\n";
List <Attribute> attrs = node.getAttributes();
for(int k = 0; k < attrs.size(); k++){
Attribute attr = attrs.get(k);
output += "The " + k + 1 + "attribute is " + attr.getName();
output += " the value is: " + attr.getValue() + "\r\n";
}
List <Element> childrenList = node.getChildren();
for(int j = 0; j < childrenList.size(); j++){
Element childNode = childrenList.get(j);
output += "The " + j + 1 + "subNode is: " + childNode.getName();
output += " value is " + childNode.getValue() + "\r\n";
}
}
System.out.println(output);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JDom解析XML(SAX方式)
import org.jdom.input.*;
import org.jdom.*;
import java.io.*;
import java.util.List;
import org.apache.xerces.parsers.*;
public class JDomSAX {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SAXBuilder builder = new SAXBuilder();
String path = "D:\\student.xml";
String output = "";
Document doc;
try {
doc = builder.build(path);
Element root = doc.getRootElement();
List <Element>children = root.getChildren();
output += "sno\t" + "name\t" + "age\t" + "course\t" + "\r\n";
for(int i = 0; i < children.size(); i++){
Element node = children.get(i);
Attribute attr = node.getAttribute("sno");
output += attr.getValue() + "\t";
output += node.getChildText("name") + "\t";
output += node.getChildText("age") + "\t";
output += node.getChildText("course") + "\r\n";
}
System.out.println(output);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="gb2312"?>
<students>
<student sno="110">
<name>Mark</name>
<age>23</age>
<course>English</course>
</student>
<student sno="114">
<name>Andy</name>
<age>19</age>
<course>Chinese</course>
</student>
</students>