import java.io.FileInputStream;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class XMLTest
{
public static void main(String[] args)
throws Exception
{
// 建立构造器
SAXBuilder sb = new SAXBuilder();
// 读入指定文件
Document doc = sb.build(new FileInputStream("src/abc.xml"));
// 获取根节点
Element root = doc.getRootElement();
// 获取所有的子节点
List list = root.getChildren();
for (int i = 0; i < list.size(); i++)
{
System.out.println("---------------------");
// 获取节点的实例
Element item = (Element)list.get(i);
// 获取属性值
String id = item.getAttribute("id").getValue();
System.out.println("id----->" + id);
// 获取当前节点的子节点
Element sub = item.getChild("title");
// 获取当前节点的值
String text = sub.getText();
System.out.println("title-->" + text);
if (item.getChild("content").getChildren().size() > 0)
{
Element sub2 = item.getChild("content").getChild("name");
String text2 = sub2.getText();
System.out.println("name --- >" + text2);
}
Element sub3 = item.getChild("email");
String text3 = sub3.getText();
System.out.println("email--->" + text3);
}
}
}
xml文件为:
<messages>
<message id="1">
<title>11</title>
<content>
<name>aa</name>
<age>23</age>
</content>
<email>33@ss.com</email>
</message>
<message id="2">
<title>44</title>
<content>
<name>bb</name>
<age>23</age>
</content>
<email>66@dd.com</email>
</message>
</messages>
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class XMLTest
{
public static void main(String[] args)
throws Exception
{
// 建立构造器
SAXBuilder sb = new SAXBuilder();
// 读入指定文件
Document doc = sb.build(new FileInputStream("src/abc.xml"));
// 获取根节点
Element root = doc.getRootElement();
// 获取所有的子节点
List list = root.getChildren();
for (int i = 0; i < list.size(); i++)
{
System.out.println("---------------------");
// 获取节点的实例
Element item = (Element)list.get(i);
// 获取属性值
String id = item.getAttribute("id").getValue();
System.out.println("id----->" + id);
// 获取当前节点的子节点
Element sub = item.getChild("title");
// 获取当前节点的值
String text = sub.getText();
System.out.println("title-->" + text);
if (item.getChild("content").getChildren().size() > 0)
{
Element sub2 = item.getChild("content").getChild("name");
String text2 = sub2.getText();
System.out.println("name --- >" + text2);
}
Element sub3 = item.getChild("email");
String text3 = sub3.getText();
System.out.println("email--->" + text3);
}
}
}
xml文件为:
<messages>
<message id="1">
<title>11</title>
<content>
<name>aa</name>
<age>23</age>
</content>
<email>33@ss.com</email>
</message>
<message id="2">
<title>44</title>
<content>
<name>bb</name>
<age>23</age>
</content>
<email>66@dd.com</email>
</message>
</messages>