1、这里使用的XML文档为students.xml
具体如下:注意空白行
<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="UTF-8"?> <?xml-sytlesheet type="text/xsl" href="students.xsl"?> <students> <student sn="01"> <name>张三</name> <age>18</age> </student> <student sn="02"> <name>李四 </name> <age>20</age> </student> </students> <!--注意这里,student结点下面有5个子节点,分别是文本结点,name,文本,age,文本,而name结点只有1个子节点 文本,值为张三,因为空白文本和文本可以合并--></span>
程序如下:
<span style="font-family:Microsoft YaHei;">package MyXMLFactory; 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 MyXMLFactory { public static void main(String[] args) throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); System.out.println("XML解析器工厂类为:" + dbf.getClass().getName()); DocumentBuilder db = dbf.newDocumentBuilder(); System.out.println("DOM解析器类为:" + db.getClass().getName()); try { Document document = db.parse(new File("D:/JavaTest/students.xml")); NodeList nl = document.getElementsByTagName("student"); for(int i=0; i<nl.getLength(); i++){ Element student = (Element)nl.item(i); Element elName = (Element)student.getElementsByTagName("name").item(0); Element elAge = (Element)student.getElementsByTagName("age").item(0); NodeList elNameChilds = elName.getChildNodes(); NodeList stuChilds = student.getChildNodes(); for(int j = 0; j<stuChilds.getLength(); j++){ Node child = (Node)stuChilds.item(j); System.out.println("j="+ j + "--childName=" + child.getNodeName() + "--childValue=" + child.getNodeValue()+"--"); } String name = elName.getFirstChild().getNodeValue(); String age = elAge.getFirstChild().getNodeValue(); System.out.println("姓名:" + name); System.out.println("年龄:" + age); System.out.println("--------------------------"); } } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } </span>
输出为
<span style="font-family:Microsoft YaHei;">XML解析器工厂类为:com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl DOM解析器类为:com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl j=0--childName=#text--childValue= -- j=1--childName=name--childValue=null-- j=2--childName=#text--childValue= -- j=3--childName=age--childValue=null-- j=4--childName=#text--childValue= -- 姓名:张三 年龄:18 -------------------------- j=0--childName=#text--childValue= -- j=1--childName=name--childValue=null-- j=2--childName=#text--childValue= -- j=3--childName=age--childValue=null-- j=4--childName=#text--childValue= -- 姓名:李四 年龄:20 -------------------------- </span>原文链接:https://www.f2er.com/xml/298067.html