问答详情
源自:2-3 使用 DOM 解析XML 文件的节点名和节点值

哈哈哈哈哈哈

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.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class bookparse {

public static void main(String[] args) {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

DocumentBuilder db = dbf.newDocumentBuilder();

Document document = db.parse("src/lib/book.xml");

NodeList booklist = document.getElementsByTagName("book");

for (int i = 0; i < booklist.getLength(); i++) {

Node node = booklist.item(i);

NamedNodeMap nnms = node.getAttributes();

System.out.println("第" + (i + 1) + "本书:");

for (int j = 0; j < nnms.getLength(); j++) {

NodeList bookchild = node.getChildNodes();


for (int k = 0; k < bookchild.getLength(); k++) {

Node bookvalue = bookchild.item(k);

if (bookvalue.getNodeType() == Node.ELEMENT_NODE) {

System.out.print(bookvalue.getNodeName() + ":");

System.out.println(bookvalue.getTextContent());

}

}

}

System.out.println("");

}

} catch (SAXException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (ParserConfigurationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}



提问者:qq_從南_nqCMU0 2019-01-23 13:27

个回答

  • 慕粉0841308050
    2019-01-24 18:19:16

    嘿嘿嘿嘿嘿嘿嘿