/* 解析netct.xml,把文件的属性和节点取出来 */
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class Test
{
private Document document=null;
//负责初始化xml文件,产生一个相对应的Document
//Document就可看作是xml文件在内存的一个引用
//通过该引用我们可以对xml这个文件进行一系列的操作
//如读写操作
public void init(String xmlFile)throws Exception{
//先获得一个DocumentBuilderFactory的实例(本身就是一个专门用来产生
//DocumentBuilder的一个工厂)
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
//拿到工厂实例后就可以生产实例----DocumentBuilder
DocumentBuilder builder=factory.newDocumentBuilder();
//DocumentBuilder可以解析xml文件,只要把相头的xml
//文件交给它的parse方法,那么它就会帮你解析,阈且产生
//一个该文件在内存中的应用---Document
document=builder.parse(xmlFile);
}
//利用document对xml文件进行读操作,把xml属性和值读出来,
//并打印在控制台
public void viewXML()throws Exception
{
//每个xml文件都有且公有一个根元素,先把这个根元素的名字打出来
Element root=document.getDocumentElement();
System.out.println("根元素是:"+root.getNodeName());
//取父节点(相对于字节点来说)
//传入节点名字,返回节点链表,一般长度是1
//如果该xml文件有两个同名的节点,那么该节点链的长度才为2
NodeList list=root.getElementsByTagName("dbstore");
System.out.println("节点链的长度是:"+list.getLength());
//拿到该节点的第一个节点:item(0)0是下标
Node fatherNode=list.item(0);
System.out.println("父节点为:"+fatherNode.getNodeName());
//获取父节点的属性值
NamedNodeMap attributes=fatherNode.getAttributes();
//有可能有多个属性,因此该解析器把解析出来的属性装在一个集合里面
for(int i=0;i<attributes.getLength();i++)
{
Node attribute = attributes.item(i);
System.out.println("属性名为:"+attribute.getNodeName()+"属性值为:"+attribute.getNodeValue());
}
NodeList childList=fatherNode.getChildNodes();
System.out.println("子节点链的长度为:"+childList.getLength());
//解析器把空格也解析成element,所有子节点链都算上
//过滤空格
for(int j=0;j<childList.getLength();j++)
{
Node childNode=childList.item(j);
//如果该节点不是一个元素(Element)则应该过滤
if(childNode instanceof Element)
{
//System.out.println("节点的名字:"+childNode.getNodeName()+"与之对应的节点值:"+childNode.getNodeValue());
//getNodeValue()获取的只是<class_anme>里面的属性值,要使用getFirtstChild()跳出<class_name>标签
System.out.println("节点的名字:"+childNode.getNodeName()+"与之对应的节点值:"+childNode.getFirstChild().getNodeValue());
}
}
}
public static void main(String[] args)throws Exception
{
Test test=new Test();
test.init("netct.xml");
test.viewXML();
}
}
///////
<?xml version="1.0" encoding="UTF-8"?>
<netctoss>
<gather single="false">
<className>org.bazu.gathersystem.gather.GatherImpl</className>
<pointfile>d://point.txt</pointfile>
<temp7file>d://temp7.txt</temp7file>
<wtmpxfile>d://wtmpx.txt</wtmpxfile>
</gather>
<db single="false">
<className>org.bazu.gathersystem.dbstore.DBStoreImpl</className>
<methodName>getInstance</methodName>
<batchSize>10</batchSize>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>jdbc:oracle:thin:@192.168.2.100:1521:tarena</url>
<username>tarena</username>
<password>tarena</password>
</db>
</netctoss>