1 import java.io.File; 2 import java.io.IOException; 3 import javax.xml.parsers.DocumentBuilder; 4 import javax.xml.parsers.DocumentBuilderFactory; 5 import javax.xml.parsers.ParserConfigurationException; 6 import org.w3c.dom.Document; 7 import org.w3c.dom.Element; 8 import org.w3c.dom.Node; 9 import org.w3c.dom.NodeList;10 import org.xml.sax.SAXException;11 12 public class XmlTest {13 14 public static void main(String[] args) {15 16 try {17 18 DocumentBuilderFactory builderFactory = DocumentBuilderFactory19 .newInstance();20 DocumentBuilder builder = builderFactory.newDocumentBuilder();21 Document document = builder.parse(new File("NewFile.xml"));22 Element root = document.getDocumentElement();23 System.out.PRintln(root.getAttribute("name")+":");24 NodeList list = root.getElementsByTagName("student");25 for (int i = 0; i < list.getLength(); i++) {26 Element student = (Element) list.item(i);27 System.out.println("-----------------------");28 System.out.println("id= " + student.getAttribute("id"));29 NodeList clist = student.getChildNodes();30 for (int j = 0; j < clist.getLength(); j++) {31 Node c = clist.item(j);32 if (c instanceof Element) {33 System.out.println(c.getNodeName() + "="34 + c.getTextContent());35 }36 }37 }38 39 } catch (ParserConfigurationException e) {40 e.printStackTrace();41 } catch (SAXException e) {42 e.printStackTrace();43 } catch (IOException e) {44 e.printStackTrace();45 }46 47 }48 }
被解析的XML:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <root name="StudentInformation"> 3 <student id="1"> 4 <name>张三</name> 5 <address>北京</address> 6 </student> 7 <student id="2"> 8 <name>李四</name> 9 <address>上海</address>10 </student>11 <student id="3">12 <name>王五</name>13 <address>广州</address>14 </student>15 </root>
显示结果:
StudentInformation:-----------------------id= 1name=张三address=北京-----------------------id= 2name=李四address=上海-----------------------id= 3name=王五address=广州
新闻热点
疑难解答