public static void main(String[] args)
{
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(new File("C:\\Users\\Administrator\\Desktop\\test.xml"));
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 获取根元素
Element root = document.getRootElement();
System.out.println("Root: " + root.getName());
// 获取所有子元素
List<Element> childList = root.elements();
System.out.println("total child count: " + childList.size());
// 获取特定名称的子元素
List<Element> childList2 = root.elements("hello");
System.out.println("hello child: " + childList2.size());
System.out.println("迭代输出-----------------------");
// 迭代输出
for (Iterator<Element> iter = childList.iterator(); iter.hasNext();)
{
Element e = iter.next();
System.out.println(e.getText());
}
System.out.println("用DOMReader-----------------------");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(new File("C:\\Users\\Administrator\\Desktop\\test.xml"));
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 获取根元素
Element root = document.getRootElement();
System.out.println("Root: " + root.getName());
// 获取所有子元素
List<Element> childList = root.elements();
System.out.println("total child count: " + childList.size());
// 获取特定名称的子元素
List<Element> childList2 = root.elements("hello");
System.out.println("hello child: " + childList2.size());
System.out.println("迭代输出-----------------------");
// 迭代输出
for (Iterator<Element> iter = childList.iterator(); iter.hasNext();)
{
Element e = iter.next();
System.out.println(e.getText());
}
System.out.println("用DOMReader-----------------------");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}