使用javax(java扩展包)中的工具解析XML字符串

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;

import java.text.SimpleDateFormat;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

 

/**
  * 功能描述:根据提供的xml信息解析xml字符串
  * @param  info        信息
  * @param  type       类型
  * @return
  */
 public void parseXmlString(String info) throws Exception {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   //创建解析器工厂
      DocumentBuilder db = dbf.newDocumentBuilder();    //通过解析器工厂创建一个解析器

      //转换xml串的两种方法

      1)InputStream is = new ByteArrayInputStream(info.getBytes());  //将xml串转化为InputStream流
      2)InputSource is = new InputSource(new StringReader(info));
      Document document = db.parse(is);     //将InputStream流转化为Document

 

      //将xml串解析出来的信息加入相应的实体Bean
      NodeList notices = document.getElementsByTagName("notice");
      for(int i=0; i<notices.getLength(); i++){
            Element notice = (Element)notices.item(i);
            Jobnotice jobnotice = new Jobnotice();
            jobnotice.setTitle(getNodeValue(notice, "title"));
            jobnotice.setOperatetime(new SimpleDateFormat("yyyyMMdd").parse(getNodeValue(notice, "operatetime")));//注意时间格式的转换
            jobnotice.setContent(getNodeValue(notice, "content"));

            jobnotice.setProgress(getNodeValue(notice, "progress"));
            noticeList.add(jobnotice);
      }
  }

 

 /**
  * 功能描述:根据标签name获取相应的Value 
  * @param info                 元素
  * @param nodeName        标签name
  * @return
  */
 public String getNodeValue(Element info, String nodeName) {
      return ((Element) info.getElementsByTagName(nodeName).item(0)).getTextContent();
 }

-------------------------------------------------代码调用测试------------------------------------------------

public class Test {

      private static String info = "<root><notice><title>公告标题</title><operatetime>20110506</operatetime>" +
 "<content>公告内容</content><progress>招聘流程</progress></notice></root>"; 
      public static void main(String[] args) throws Exception{
            parseXmlString(info);
      }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值