jdom解析xml小例子

首先要导入jdom的相关jar包

 

package test;

import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class Explain {
   //xml文件路径
   private static String proXMLPath="../test/src/test/SyncProtocol.xml";
   public static void main(String args[]) throws JDOMException, IOException{
    String num = "";
    SAXBuilder builder = new SAXBuilder();
    //得到文档对象
          Document doc = builder.build(proXMLPath);
       //获取文档根元素
    Element root = doc.getRootElement();
    //获取根元素的子元素
          List elementList = root.getChildren();
          Element areaname = null;
          for (int i = 0; i < elementList.size(); i++) {
           //得到元素对象
              Element temp = (Element) elementList.get(i);
              //得到元素中属性名为name的值
              String name = temp.getAttributeValue("name");
              if (name.equals("shenyang")) {
               areaname = temp;
               //得到属性值为id的值
                  num = temp.getAttributeValue("id");
                  System.out.println(num);
                  break;
                  }
          }          
   }
}
}

 

你可能感兴趣的:(dom解析xml)