java读取xml

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class MyTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String dataXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<root>" +
"<head>" +
"</head>" +
"<body>" +
"<parameter>" +
"<NAME>李俊华</NAME>" +
"<SEX>2</SEX>" +
"<SEX_NAME>女</SEX_NAME> "+
"<BIRTHDAY>19780708</BIRTHDAY>" +
"<TELEPHONE></TELEPHONE>" +
"<ADDRESS></ADDRESS>" +
"<REGION_CODE>130207</REGION_CODE>" +
"<UPLOAD_ORGANIZATION_CODE>新农合</UPLOAD_ORGANIZATION_CODE>" +
"<UPLOAD_ORGANIZATION_NAME>新农合</UPLOAD_ORGANIZATION_NAME>" +
"<zjlx>" +
"<CERT_TYPE>0_01</CERT_TYPE>" +
"<CERT_NUMBER>130222198006031620</CERT_NUMBER>" +
"<CERT_NAME>居民身份证</CERT_NAME>" +
"</zjlx>" +
"</parameter>" +
"</body>" +
"</root>";
HashMap hashMap = new HashMap();
ByteArrayInputStream byteArrayInputStream = null;
Document document = null;
SAXReader saxReader = new SAXReader();
Element root = null;
Element nodeElement = null;

try {
//将xml转成UTF-8的流
byteArrayInputStream = new ByteArrayInputStream(dataXml.getBytes("UTF-8"));
//利用dom4j将流读写成document形式
document = saxReader.read(byteArrayInputStream);
//获得root节点
root = document.getRootElement();
//利用root获取指定节点
nodeElement = (Element) root.selectSingleNode("/root/body/parameter");

List childNode = nodeElement.elements();
int childNodeSize = childNode.size();
//将指定节点下的属性保存到hashmap中
for(int i=0;i<childNodeSize;i++)
{
Element oneChildNode = (Element)childNode.get(i);
hashMap.put(oneChildNode.getName(), oneChildNode.getText());
}

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
if (byteArrayInputStream != null)
{
try {
byteArrayInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byteArrayInputStream = null;
}
root.clearContent();
root = null;
nodeElement = null;
document = null;
saxReader = null;
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值