package liu.dh.xml;
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Demo1_Dom {
/**
* xml的dom解析
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//通过工厂方法获取dom解析器
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db= dbf.newDocumentBuilder();
//获取document对象
//创建文档对象
File file = new File("src\\liu\\dh\\xml\\test1.xml");
Document document = db.parse(file);
//System.out.println(document);
//通过标签获取节点集合
NodeList nodes= document.getElementsByTagName("book");
//向下转型,将Node转换为Element,获取节点元素
Element element = (Element) nodes.item(0);
System.out.println(element.getTextContent());
Element element2 = (Element) element.getElementsByTagName("title").item(0);
//System.out.println(element2.getTextContent());
//获取节点属性
String nameString = element.getAttribute("category");
System.out.println("-----------------------");
System.out.println(nameString);
//获取文档节点集合e
getNode(document,0);
}
//遍历元素节点,分层次显示节点
private static void getNode(Node node2,int level) {
//判断节点是否是元素类型,是就输出:判断节点,因为节点包含很多
if (node2.getNodeType()==node2.ELEMENT_NODE) {
System.out.println(getLevel(level)+"节点名字"+node2.getNodeName());
}
level++;
//获取子节点集合
NodeList list = node2.getChildNodes();
System.out.println(list.getLength());
//遍历集合
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
//递归
getNode(node,level);
}
}
//定义层次显示方法
public static String getLevel(int level){
StringBuffer sBuffer = new StringBuffer();
for (int i = 1; i <= level; i++) {
sBuffer.append("---");
}
return sBuffer.toString();
}
}
|
|