XML文件如下:person.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <employees>
- <employee>
- <name pinyin="zhangsan">张三</name>
- <sex>m</sex>
- <age>30</age>
- </employee>
- <employee>
- <name pingyin="tom">tom</name>
- <sex>w</sex>
- <age>20</age>
- </employee>
- </employees>
使用jdom来解析必须要有jdom的插件包,附件中已经上传
JAVA实现代码
- import java.io.File;
- import java.io.IOException;
- import java.util.List;
- import org.jdom.Attribute;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.JDOMException;
- import org.jdom.input.SAXBuilder;
- public class JDOMxml {
- public static void main(String[] args) {
- String path = Class.class.getResource("/").getPath();
- SAXBuilder builder = new SAXBuilder();
- try {
- Document doc = builder.build(new File(path+"person.xml"));
- Element foo = doc.getRootElement();
- List allChildren = foo.getChildren();
- for(int i=0;i<allChildren.size();i++) {
- Element it = (Element) allChildren.get(i);//获得的是employee节点
- Element its = it.getChild("name");
- List list = its.getAttributes();
- for (int j = 0; j < list.size(); j++) {
- Attribute att = (Attribute) list.get(j);
- System.out.println("属性:"+att.getValue());
- }
- // System.out.println(its.getAttributeValue("name", "pinyin"));
- System.out.println("名字:" + ((Element)allChildren.get(i)).getChild("name").getText());
- System.out.println("性别:" + ((Element)allChildren.get(i)).getChild("sex").getText());
- System.out.println("年龄:" + ((Element)allChildren.get(i)).getChild("age").getText());
- }
- } catch (JDOMException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }