package common;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
*利用dom解析xml文件
*/
public class XMLtest {
public static DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
public static void main(String[] args) {
String path = XMLtest.class.getResource("").getPath();
File file = new File(path + "//Orapara.xml");
// NamedNodeMap attributes = root.getAttributes();
// System.out.println(attributes.getLength());
// for(int i=0;i<attributes.getLength();i++){
// Node attribute = attributes.item(i);
// String name = attribute.getNodeName();
// String value = attribute.getNodeValue();
// System.out.println(name+"-"+value);
// }
// for(Node node = root.getFirstChild();node!=null;node =
// node.getNextSibling()){
// String name = node.getNodeName();
// String value = node.getNodeValue();
// System.out.println(name+"-"+value);
// }
searchall(file);
}
public static void searchall(File file) {
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
Element root = doc.getDocumentElement();
//获取指定的值
NodeList list = root.getElementsByTagName("position");
System.out.println(list.item(0).getTextContent());
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
getElementChild(node);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//对一个elment做递归调用
public static void getElementChild(Node nodeElement){
if (nodeElement instanceof Element) {
if (nodeElement.getChildNodes().getLength()<=1) {
String name = nodeElement.getNodeName();
String value = nodeElement.getTextContent();
System.out.println(name + "-" + value);
} else {
NodeList childnodes = nodeElement.getChildNodes();
for(int i=0;i<childnodes.getLength();i++){
getElementChild(childnodes.item(i));
}
}
}
}
}
下面是XML的内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<oracle name="ora10g">
<storage>
<ram unit="mb">1024</ram>
<rom unit="mb">20480</rom>
</storage>
<file-position>
<content>F://myfile</content>
<log>
<max-size unit="mb">2048</max-size>
<position>F://logfile</position>
</log>
</file-position>
</oracle>
dom解析一个XMl
最新推荐文章于 2023-06-19 16:47:21 发布