DOM解析XML例子

例1:缩进式XML

	 import javax.xml.parsers.*;
	 import org.w3c.dom.*;
	 import java.io.*;
	  
	 public class DOMPageList{
	   public static void main(String[] args) {
	     try {
	       //创建解析工厂
	       DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
	       //指定DocumentBuilder
	       DocumentBuilder builder = dbfactory.newDocumentBuilder();
	       //从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了
	       Document doc = builder.parse(new File("book.xml"));
	       //得到Document的根(节点名:book)
	       Element root = doc.getDocumentElement();
	       System.out.println("根节点标记名:" + root.getTagName());
	       System.out.println("*****下面遍历XML元素*****");
	       //获得page元素
	       NodeList list = root.getElementsByTagName("content");
	       System.out.println(list.getLength());
	       //遍历page元素
	       for (int i=0; i < list.getLength() ; i++) {
	      //获得page的元素
	         Element element = (Element)list.item(i);
	         //获得ID属性
	         NodeList titleid = element.getElementsByTagName("id");
	         //获得id元素
	         Element idElement = (Element)titleid.item(0);
	         //获得id元素的第一个值
	         String id = idElement.getFirstChild().getNodeValue();
	         System.out.println("ID :" + "   " + id  + "title :"  + "   " + title  +  "file :" + "   " + file);
	       }
	     } catch (Exception e) {
	       e.printStackTrace();
	     }
	   }


book.xml:
<?xml version="1.0" encoding="UTF-8"?>
 <book>
 <content>
  <id>100010</id> 
  <title>java tools</title> 
  <file>c:\file\</file> 
  </content>
 </book>

例2:横排式xml:
 try {
	       DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
	       DocumentBuilder builder = dbfactory.newDocumentBuilder();
	       Document doc = builder.parse(new File("book.xml"));   
	       Element root = doc.getDocumentElement();
	       NodeList list = root.getElementsByTagName("xml");  
	       Node node = null; 
	       String name = "";
	       for(int i=0;i<list.getLength();i++){
	    	   node = list.item(i);
	    	   name = node.getAttributes().getNamedItem("name").getNodeValue();
	    	   System.out.println("可以得到属性name的值:"+name);
	      }
	     } catch (Exception e) {
	       e.printStackTrace();
	     }

book.xml:
<?xml version="1.0" encoding="UTF-8"?>
<xmlbody>
<xml id="1,3,4" name="张三"  />
<xml id="11,33,44" name="李四" />
</xmlbody>

你可能感兴趣的:(C++,c,xml,C#)