DOM解析XML文档

  1. package com.xml.test;
  2. /**
  3.  * <p>
  4.  * Title: DomXMLParser.class
  5.  * </p>
  6.  * <p>
  7.  * Description: DOM解析XML文档
  8.  * </p>
  9.  * 
  10.  * @author apple90
  11.  * @version 1.0
  12.  * @since Sep 11, 2008
  13.  */
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import javax.xml.parsers.DocumentBuilder;
  17. import javax.xml.parsers.DocumentBuilderFactory;
  18. import org.w3c.dom.Document;
  19. import org.w3c.dom.NodeList;
  20. public class DomXMLParser {
  21.     public static void main(String arge[]) throws Exception {
  22.         try {
  23.             File xmlFile = new File("src/com/xml/test/employee.xml");
  24.             File txtFile = new File("g://test.txt");
  25.             FileOutputStream fos = new FileOutputStream(txtFile);
  26.             DocumentBuilderFactory factory = DocumentBuilderFactory
  27.                     .newInstance();
  28.             DocumentBuilder builder = factory.newDocumentBuilder();
  29.             Document document = builder.parse(xmlFile);
  30.             NodeList nodeList = document.getElementsByTagName("employee");
  31.             for (int i = 0; i < nodeList.getLength(); i++) {
  32.                 byte[] buf = ("员工姓名:"
  33.                         + document.getElementsByTagName("name").item(i)
  34.                                 .getFirstChild().getNodeValue() + "/r/n")
  35.                         .getBytes();
  36.                 fos.write(buf);
  37.                 buf = (" 员工所在部门:"
  38.                         + document.getElementsByTagName("department").item(i)
  39.                                 .getFirstChild().getNodeValue() + "/r/n")
  40.                         .getBytes();
  41.                 fos.write(buf);
  42.             }
  43.         } catch (Exception e) {
  44.             e.printStackTrace();
  45.         }
  46.     }
  47. }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值