XML之DOM基本操作

package src.dom;

import javax.xml.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

public class DomUtil {
private static String XML = "dom.xml";
private StringBuffer sb = new StringBuffer();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

//得到DOM树
public Document getDocument() throws Exception{

Document doc=null;
DocumentBuilder builder = null ;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try{
builder = docFactory.newDocumentBuilder();
}catch(ParserConfigurationException e){

}
InputStream is = DomUtil.class.getClassLoader().getResourceAsStream("src/dom/"+XML);

if(is==null){
throw new FileNotFoundException("找不到:"+XML);
}
doc = builder.parse(is);
doc.normalize();
return doc;
}

/**
* 访问标签名为TAGNAME的第一个节点
* @param doc
* @param tagName
* @return
*/
public Node visitFirstNode(Document doc,String tagName){
NodeList nodeL = doc.getElementsByTagName(tagName);
Node node=null;
if(nodeL!=null){
node = nodeL.item(0);
}
return node;

}

/**
* 遍历节点下的怕有子节点
* @param node
*/
public void searchAllElement(Node node){
if(node!=null){
sb.append("\n name:"+node.getNodeName()+" type:"+node.getNodeType());
if(node.hasChildNodes()){
NodeList nodeL = node.getChildNodes();

for(int i=0;i<nodeL.getLength();i++){
searchAllElement(nodeL.item(i));
}
}
}
}



/**
* 访问节点的属性
* @param node
*/
public void visitNode(Node node){
if(node!=null){
sb.append("\n name:"+node.getNodeName()+" type:"+node.getNodeType());
if(node.hasChildNodes()){
if(node.getFirstChild().getNodeType()==Node.TEXT_NODE){//节点有文本
sb.append(" text value:"+node.getFirstChild().getNodeValue());
}
}
if(node.hasAttributes()){//访问属性
NamedNodeMap map = node.getAttributes();
for(int index=0;index<map.getLength();index++){
Node att = map.item(index);
sb.append("\n================= name:"+att.getNodeName()+" value:"+att.getNodeValue());
//Attr att = (Attr)map.getNamedItem("type");
//sb.append(" att name:"+att.getName()+" value:"+att.getValue());
}
}

}

sb.append("node is null");
}

/**
* 访问节点相监的节点
* @param node
*/
public void visitBrotherNode(Node node){
Node preNode = node.getPreviousSibling();
if(preNode!=null){
visitNode(preNode);
}

Node nextNode = node.getNextSibling();
if(nextNode != null){
visitNode(nextNode);
}
}

/**
* 得到节点名称
* @param node
* @return
*/
public String getName(Node node){
return node.getNodeName();
}
/**
* 节点的文本内容
* @param node
* @return
*/
public String getText(Node node){
if(node.hasChildNodes()){
if(node.getFirstChild().getNodeType()==Node.TEXT_NODE){
return node.getFirstChild().getNodeValue();
}
}
if(node.getNodeType()==Node.TEXT_NODE){
return node.getNodeValue();
}
return null;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值