import java.io.FileInputStream; import java.io.FileNotFoundException; 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 ReadXML { public static void main(String[] args) { try { // 得到DOM解析器的工厂实例 DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); // 从DOM工厂获得DOM解析器 DocumentBuilder dombuilder = domfac.newDocumentBuilder(); // 把要解析的XML文档转化为输入流,以便DOM解析器解析它 InputStream is = new FileInputStream("test.xml"); // 解析XML文档的输入流,得到一个Document Document doc = dombuilder.parse(is); // 得到XML文档的根节点 Element root = doc.getDocumentElement(); // 得到节点的子节点 NodeList books = root.getChildNodes(); if (books != null) { // 轮循子节点 for (int i = 0; i < books.getLength(); i++) { // 获取book节点 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.getFirstChild() .getNodeValue(); System.out.println(name); } if (node.getNodeName().equals("price")) { // 获得节点的文本值 String price = node.getFirstChild() .getNodeValue(); System.out.println(price); } } } } } } } // 异常处理 catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
- 粉丝: 0
- 资源: 2
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助