java解析xml文檔

來源:互聯網
上載者:User

以上,是我的最終運行結果。

為了以後鞏固學習,特把它貼在這裡,以便日後翻閱。

 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,也就是我們所需要的值

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.