以上,是我的最終運行結果。
為了以後鞏固學習,特把它貼在這裡,以便日後翻閱。
1.library.xml:
<?xml version="1.0" encoding="gb2312"?>
<books>
<book email="zhangyupeng_good">
<name>Java</name>
<price>100.00</price>
</book>
</books>
2.DomParse.java:(用記事本編寫就可以了)import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;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 DomParse {public DomParse() {DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();try {DocumentBuilder dombuilder = domfac.newDocumentBuilder();InputStream is = new FileInputStream("D:/張鑫xml視頻教程/XML方面的例子和做的題目/java解析xml文檔/library.xml");Document doc = dombuilder.parse(is);Element root = doc.getDocumentElement();NodeList books = root.getChildNodes();if (books != null) {for (int i = 0; i < books.getLength(); i++) {Node book = books.item(i);if (book.getNodeType() == Node.ELEMENT_NODE) {String email = book.getAttributes().getNamedItem("email").getNodeValue();System.out.println(email);for (Node node = book.getFirstChild(); node != null; node = node.getNextSibling()) {if (node.getNodeType() == Node.ELEMENT_NODE) {if (node.getNodeName().equals("name")) {String name = node.getNodeValue();String name1 = node.getFirstChild().getNodeValue();System.out.println(name);System.out.println(name1);}if (node.getNodeName().equals("price")) {String price = node.getFirstChild().getNodeValue();System.out.println(price);}}}}}}} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void main(String args[]) {new DomParse();}}3.編譯:javac DomParse.java4.運行:java DomParse library.xml,就可以看到一開始的結果。大家會看到有一個null值,那是由於下面這兩行代碼導致的:String name = node.getNodeValue();———>輸出null值String name1 = node.getFirstChild().getNodeValue();--------->輸出Java,也就是我們所需要的值