hooyantsing's Blog

XML_DOM_解析

字数统计: 187阅读时长: 1 min
2019/12/22

XML DOM 解析

样品

1
2
3
4
5
6
7
8
<mime-mapping>
    <extension>htm</extension>
    <mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
    <extension>html</extension>
    <mime-type>text/html</mime-type>
</mime-mapping>

解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
           // 创建解析器工厂
           DocumentBuilderFactory factory =  DocumentBuilderFactory.newInstance();
           // 通过解析器工厂创建dom解析器
           DocumentBuilder builder =  factory.newDocumentBuilder();
           // 获取xml文件路径,生成Document对象
           Document doc =  builder.parse("src/web.xml");
           NodeList node =  doc.getElementsByTagName("mime-mapping");
           webXML = new HashMap<String,  String>();
           for (int i = 0; i <  node.getLength(); i++) {
               Element e = (Element)  node.item(i);
               String webXMLsuffix =  e.getElementsByTagName("extension").item(0).getFirstChild().getNodeValue();
               String webXMLtype =  e.getElementsByTagName("mime-type").item(0).getFirstChild().getNodeValue();
               //System.out.println("文件后缀:" + webXMLsuffix);
               //System.out.println("http格式:" + webXMLtype);
               webXML.put(webXMLsuffix,  webXMLtype);
           }
CATALOG