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

}

}

你可能感兴趣的:(java,xml)