dom4j解析xml文件

使用的xml文件与创建xml所使用的相同

 

<?xml version="1.0" encoding="UTF-8"?>

<devices>
  <!--An XML devices-->
  <device id="generic_web_browser" user_agent="DO_NOT_MATCH_GENERIC_WEB_BROWSER">
    <group id="pdf">
      <capability>Dom4j Create XML Schema</capability>
      <author>
        <fistname>Allen</fistname>
        <lastname>Jon</lastname>
      </author>
    </group>
  </device>
</devices>
 

 

使用dom4j解析xml文件import java.io.File;

import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DOMAnalysisXml {
	
	@SuppressWarnings("unchecked")
	public void analysisXml(String fileName) {
		 SAXReader saxReader = new SAXReader();
		 try {
			Document document = saxReader.read(new File(fileName));
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			Iterator<Element> it = elements.iterator();
			while(it.hasNext()) {
				Element e = it.next();
				System.out.println(e.getName() + " : " + e.attribute("id").getValue() + " -- " + e.attribute("user_agent").getValue());
				List<Element> group = e.elements();
				Iterator<Element> git = group.iterator();
				//所有的过程其实就是层层解析的过程
				while(git.hasNext()) {
					Element ge = git.next();
					//通过使用e.attribute(" ").getValue()获得属性的值
					System.out.println(ge.getName() + " : " + e.attribute("id").getValue());
					List<Element> caps = ge.elements();
					Iterator<Element> cit = caps.iterator();
					while(cit.hasNext()) {
						Element ce = cit.next();
						if("capability".equals(ce.getName())) {
							//通过该ce.getText()获得值
							System.out.println(ce.getText());
						} else {
							Iterator<Element> nit = ce.elements().iterator();
							while(nit.hasNext()) {
								Element ne = nit.next();
								System.out.println(ne.getText());
							}
						}
					}
				}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String fileName = "E:/test.xml";
		new DOMAnalysisXml().analysisXml(fileName);
	}
}

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