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);
}
}