@SuppressWarnings("unchecked")
public void parseByJDOM()
{
SAXBuilder sax = new SAXBuilder();
try
{
String xmlFilePath = System.getProperty("user.dir")
+ File.separator + "config" + File.separator + "test.xml";
Document document = sax.build(xmlFilePath); //加载XML文件
Element rootElement = document.getRootElement(); //得到根节点
List<Element> firstList = rootElement.getChildren(); //得到所有的第二层节点
if(null == firstList || firstList.isEmpty())
{
return;
}
for (int i = 0; i < firstList.size(); i++)
{
Element secondElement = (Element) firstList.get(i); //得到第二层的单个节点
System.out.println(secondElement.getName()); //打印第二层节点的名称
List attributeList = secondElement.getAttributes(); //得到第二层节点的所有属性
if(null!=attributeList && !attributeList.isEmpty())
{
for(int j=0;j<attributeList.size();j++)
{
Attribute attribute = (Attribute) attributeList.get(j); //通过循环得到每个单一的属性
System.out.println("name:"+attribute.getName()+",value:"+attribute.getValue()); //打印属性的name和value
}
}
List<Element> thirdElementList = secondElement.getChildren(); //得到所有的第三层节点
if(null == thirdElementList || thirdElementList.isEmpty())
{
continue;
}
for(int j=0;j<thirdElementList.size();j++)
{
Element thirdElement = thirdElementList.get(j);
System.out.println("text:"+thirdElement.getText()); //答应第三层节点的Text内容
}
}
}
catch (JDOMException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}