读取language.xml
<pre name="code" class="java"><span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?> <Languages cat="it"> <lan id="1"> <name>Java</name> <ide>Eclipse</ide> </lan> <lan id="2"> <name>Swift</name> <ide>Xcode</ide> </lan> <lan id="3"> <name>C#</name> <ide>Visual Studio</ide> </lan> </Languages></span>
测试代码如下:
<strong><span style="font-size:18px;">package com.demo; import java.io.File; import java.io.IOException; 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; import org.xml.sax.SAXException; public class readxml { public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("languages.xml")); //获得根节点 Element root = document.getDocumentElement(); System.out.println("cat = " + root.getAttribute("cat")); NodeList list = root.getElementsByTagName("lan"); for (int i = 0; i < list.getLength(); i++) { Element lan = (Element) list.item(i); System.out.println("---------------------"); System.out.println("id = " + lan.getAttribute("id")); //这样的方法getElementsByTagName()返回的是nodelist还需要取第一个值item(0),这种做法不好 // Element name = (Element) lan.getElementsByTagName("name").item(0); // System.out.println("name = " + name.getTextContent()); // Element ide = (Element) lan.getElementsByTagName("ide").item(0); // System.out.println("ide = " + ide.getTextContent()); //由每一个父节点获取到相应所有子节点,再循环取值 NodeList clist = lan.getChildNodes(); for (int j = 0; j < clist.getLength(); j++) { Node node = clist.item(j); //在读取xml文件时<>与<>中间的空白部分也会被识别出来,因此通过一判断是否为元素而排出空白部分 //不理解的话可以试着把判断删掉。就会把空白部分以text= 的形式打印出来 if (node instanceof Element) { System.out.println(node.getNodeName() + " = " + node.getTextContent()); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }</span></strong>
运行结果如下
cat = it
---------------------
id = 1
name = Java
ide = Eclipse
---------------------
id = 2
name = Swift
ide = Xcode
---------------------
id = 3
name = C#
ide = Visual Studio