DOM 实例

来源:互联网 发布:linux jdk 下载 编辑:程序博客网 时间:2024/05/31 13:16

 DOM:
一、读取文件
1、data.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<no>00001</no>
<name>DOM4J</name>
</book>
<book>
<no>00002</no>
<name>JDOM</name>
</book>
</books>

2、TestDOM.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class TestDOM {
public static void main(String[] args) {
        try {
         File file = new File("data.xml");
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document document = builder.parse(file);
         NodeList nodeList = document.getElementsByTagName("book");
         for(int i=0;i<nodeList.getLength();i++){
          System.out.println("NO:"+document.getElementsByTagName("no").item(i).getFirstChild().getNodeValue());
          System.out.println("NAME:"+document.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
         }
  } catch (Exception e) {
   e.printStackTrace();
  }
}
}

原创粉丝点击