标签:

DOM解析操作




只在跟节点<addresslist>下面建立一个子节点<name>
<?xml version="1.0" encoding="UTF-8"?> <addresslist> <linkman> <name>张三</name> <email>www.baidu.com</email> </linkman> <linkman> <name>李四</name> <email>www.sina.com</email> </linkman> </addresslist>
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//=================================================
// File Name : DOM_demo
//------------------------------------------------------------------------------
// Author : Common
//类名:BinarySearch_Find
//属性:
//方法:
//主类
//Function : DOM_demo
public class DOM_demo {
public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //建立DocumentBuilderFactory
DocumentBuilder builder = factory.newDocumentBuilder(); //建立DocumentBuilder
Document doc = null;
try{
doc = builder.parse("/home/common/software/coding/HelloWord/JavaWeb/bin/dom_name.xml");
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
NodeList nl = doc.getElementsByTagName("name"); //查找name节点
System.out.println("姓名:"+nl.item(1).getFirstChild().getNodeValue()); //输出第1个节点的内容
}
}
一些DOM操作,循环输出节点信息
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//=================================================
// File Name : DOM_demo
//------------------------------------------------------------------------------
// Author : Common
//类名:BinarySearch_Find
//属性:
//方法:
//主类
//Function : DOM_demo
public class DOM_demo {
public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //建立DocumentBuilderFactory
DocumentBuilder builder = factory.newDocumentBuilder(); //建立DocumentBuilder
Document doc = null;
try{
doc = builder.parse("/home/common/software/coding/HelloWord/JavaWeb/bin/dom_name.xml");
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
// NodeList nl = doc.getElementsByTagName("name"); //查找name节点
// System.out.println("姓名:"+nl.item(1).getFirstChild().getNodeValue()); //输出第1个节点的内容
NodeList lm = doc.getElementsByTagName("linkman"); //查找linkman节点
for(int i=0;i<lm.getLength();i++){
Element e = (Element)lm.item(i); //取得每一个元素
System.out.println("姓名:"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
System.out.println("邮箱:"+e.getElementsByTagName("email").item(0).getFirstChild().getNodeValue());
}
}
}
生成XML文件
标签:
原文地址:http://www.cnblogs.com/tonglin0325/p/5342957.html