1. 程式人生 > >Http+XMl報文解析常用方法示例

Http+XMl報文解析常用方法示例



解析xml檔案有四種方法:DOM、SAX、JDOM、DOM4J
利用DOM4J的方式解析本地students.xml檔案:

students.xml檔案內容如下:
//--------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student id="001">
        <name>張三</name>
        <sex>男</sex>
        <age>20</age>
    </student>
    <student id="002">
        <name>李四</name>
        <sex>女</sex>
        <age>21</age>
    </student>
</students>
//--------------------------------------------------------------

DOM4J解析
//--------------------------------------------------------------
public class dom4j02{
        public static void main(String[] args)threws Execption{
            SAXReader saxReader=new SAXReader();
            Document    document =saxReader.read("src/stu/dom4j/students.xml");
            Element rooElement=document.getRootElement();
            Iterator  iter=rooElement.elementIterator();//遍歷根節點

             Element    studentElement=(Element)iter.next();
System.out.println("ID:"+studenElement.attributeValue('id'));
System.out.println("姓名:"+studenElement.attributeValue('name'));
System.out.println("年齡:"+studenElement.attributeValue('age'));
     }
}
//--------------------------------------------------------------