package com.util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XMLUtil{
public static void element(NodeList list){
for (int i = 0; i <list.getLength() ; i++) {
Element element = (Element) list.item(i);
NodeList childNodes = element.getChildNodes();
for (int j = 0; j <childNodes.getLength() ; j++) {
if (childNodes.item(j).getNodeType()== Node.ELEMENT_NODE) {
//获取节点
System.out.println("节点:" + childNodes.item(j).getNodeName());
//获取节点值
// if (childNodes.item(j).hasChildNodes()){
Element e = (Element)childNodes.item(j);
NodeList list1 = e.getChildNodes();
// element(list1);
System.out.println("value:" + e.getAttribute("value"));
System.out.println("name:" + e.getAttribute("name"));
System.out.println();
// System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
// }
}
}
}
}
public static void node(NodeList list){
for (int i = 0; i <list.getLength() ; i++) {
Node node = list.item(i);
NodeList childNodes = node.getChildNodes();
for (int j = 0; j <childNodes.getLength() ; j++) {
if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {
System.out.print(childNodes.item(j).getNodeName() + ":");
System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
}
}
}
}
public static void main(String[] args) {
//1.创建DocumentBuilderFactory对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//2.创建DocumentBuilder对象
try {
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File("D:\\Test\\PDFParams.xml");
Document d = builder.parse(file);
NodeList sList = d.getElementsByTagName("CustomTaskParameters");
element(sList);
// node(sList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<CustomTaskParameters>
<Param name="projectname" value="Quick Start - Automotive Interactive"/>
<Param name="imagewidth" value="21.0"/>
<Param name="imageheight" value="29.7"/>
<Param name="orientation" value="LANDSCAPE"/>
<Param name="color" value="BLACK_AND_WHITE"/>
</CustomTaskParameters>
输出结果: