XML解析

package com.hutu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.hutu.po.Clerk;

public class XmlReader {

 public NodeList readXml() {
  DocumentBuilderFactory factory = null;
  DocumentBuilder builder = null;
  NodeList nodeList = null;
  FileOutputStream fileOutputStream=null;
  StringBuffer sBuffer=new StringBuffer("编号\t\t\t"+"姓名\t\t"+"性别\t\t"+"年龄\n");
  try {
   factory = DocumentBuilderFactory.newInstance();
   builder = factory.newDocumentBuilder();
   Document document = builder.parse("clerk.xml");
   Element rootElement = document.getDocumentElement();// 获取根节点
   nodeList = rootElement.getChildNodes();// 获取根节点下的子节点
   for (int i = 0; i < nodeList.getLength(); i++) {
    Clerk clerk=new Clerk();//创建对象实例
    Node node = nodeList.item(i);
    if (node.getNodeType() == node.ELEMENT_NODE) {
     // int idValue=Integer.parseInt(node.getAttributes().item(0).getNodeValue());//在不知道属性名字前提下,这样操作
     int idValue = Integer.parseInt(node.getAttributes()
       .getNamedItem("id").getNodeValue());// 在知道属性名字前提下,这样操作
     clerk.setId(idValue);//给对象 赋值
     NodeList childNodeList=node.getChildNodes();
     for(int j=0;j<childNodeList.getLength();j++){
      Node childNode=childNodeList.item(j);
      if(childNode.getNodeName().equalsIgnoreCase("name")){
       clerk.setName(childNode.getTextContent());
      }else if(childNode.getNodeName().equalsIgnoreCase("sex")){
       clerk.setSex(childNode.getTextContent());
      }else if(childNode.getNodeName().equalsIgnoreCase("age")){
       clerk.setAge(Integer.parseInt(childNode.getTextContent()));
      }
     }
//     System.out.println(clerk.getId()+"\t"+clerk.getName()+"\t"+clerk.getSex()+"\t"+clerk.getAge());
     fileOutputStream=new FileOutputStream(new File("info.txt"));
     sBuffer.append(clerk.getId()+"\t\t"+clerk.getName()+"\t\t"+clerk.getSex()+"\t\t\t"+clerk.getAge()+"\n");
     fileOutputStream.write(sBuffer.toString().getBytes());
     fileOutputStream.flush();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(fileOutputStream != null){
    try {
     fileOutputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return nodeList;
 }

 public static void main(String[] args) {
  new  XmlReader().readXml();
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值