DOM解析XML文件
程序员文章站
2022-05-29 08:17:22
...
1.DOM解析XML文件
<?xml version="1.0" encoding="UTF-8"?> <groups> <group name="group1" ap_num="3"> <ap name="ap1_1" mac="00:00:00:00:01:01" ip="127.0.1.1">1</ap> <ap name="ap1_2" mac="00:00:00:00:01:02" ip="127.0.1.2">2</ap> <ap name="ap1_3" mac="00:00:00:00:01:03" ip="127.0.1.3">3</ap> </group> <group name="group2" ap_num="4"> <ap name="ap2_1" mac="00:00:00:00:02:01" ip="127.0.2.1"></ap> <ap name="ap2_2" mac="00:00:00:00:02:02" ip="127.0.2.2"></ap> <ap name="ap2_3" mac="00:00:00:00:02:03" ip="127.0.2.3"></ap> <ap name="ap2_4" mac="00:00:00:00:02:04" ip="127.0.2.4"></ap> </group> <group name="group3" ap_num="2"> <ap name="ap3_1" mac="00:00:00:00:03:01" ip="127.0.3.1"></ap> <ap name="ap3_2" mac="00:00:00:00:03:02" ip="127.0.3.2"></ap> </group> </groups>
package dom;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomParseTest {
public void test() throws Exception{
InputStream input = this.getClass().getClassLoader().getResourceAsStream("dom/ap_group.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(input);
Element element = document.getDocumentElement();
//group 节点
NodeList groupNodes = element.getElementsByTagName("group");
for(int i=0;i<groupNodes.getLength();i++){
Element groupElement = (Element) groupNodes.item(i);
System.out.println(groupElement.getAttribute("name"));
//group下的子节点
NodeList apNodes = groupElement.getChildNodes();
System.out.println(" 字节点个数:"+apNodes.getLength());
for(int j=0;j<apNodes.getLength();j++){
if(apNodes.item(j).getNodeType()==Node.ELEMENT_NODE){
Element apElement = (Element) apNodes.item(j);
System.out.println(" value个数:"+apElement.getChildNodes().getLength());
NodeList valueNodes = apElement.getChildNodes();
for(int k=0;k<valueNodes.getLength();k++){
System.out.println(" "+valueNodes.item(k).getNodeValue());
}
System.out.println(" ap属性name值"+apElement.getAttribute("name"));
}
}
}
input.close();
}
public static void main(String[] args) {
DomParseTest test = new DomParseTest();
try {
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上一篇: Python matplotlib 绘制3D柱形图, 并修改颜色
下一篇: Dom 解析XML文件