首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

dom4j生成和好析xml

2012-10-15 
dom4j生成和解析xmlpublic class XmlTest{//创建xmlpublic static void createxml(String fileName) throw

dom4j生成和解析xml
public class XmlTest{
     //创建xml
     public static void createxml(String fileName) throws Exception {
Document document = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("ns0:UCP_TMS_08").addAttribute("xmlns:ns0", "urn:redbaby:ucp:tms:bus");
Element element = DocumentHelper.createElement("row");
element.add(DocumentHelper.createElement("name").addText("张三"));
element.add(DocumentHelper.createElement("sex").addText("男"));
element.add(DocumentHelper.createElement("age").addText("29"));
root.add(element);
document.add(root);
saveXML(fileName,document);
}
    //保存生成的xml
    public static void saveXML(String path,Document document) throws UnsupportedEncodingException{
try {
FileOutputStream fos = new FileOutputStream(path);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(fos, format);
try {
writer.write(document);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}

//解析刚才生成的xml
public static void parserXml(String path) throws Exception {
try {

SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File(path));
Node ns0Node = document.selectSingleNode("//ns0:UCP_TMS_08");
String ns0Urn = ns0Node.getDocument().getRootElement().getNamespaceURI();
if(ns0Urn!="urn:redbaby:ucp:tms:bus"){
System.out.println("根元素不对");
return;
}
System.out.println(ns0Urn);
List<Element> list = (List<Element>) document.selectNodes("//row");
if(list!=null&&list.size()>0){
totalcount += list.size();
Iterator<Element> iter = list.iterator();
String name= "";
String sex= "" ;
String age= "";
  while(iter.hasNext()){
try {
Element row = (Element)iter.next();
name= row.elementText("name");
sex = row.elementText("sex");
age= row.elementText("age");
                   System.out.println(name+"----"+sex+"----"+age)
}catch (Exception e) { e.printStackTrace();
}
System.out.println("dom4j parserXml");
}
public static void main(String[] args){
//createxml,parserXml是静态方法,不需要创建实例,运行main方法,此时看E下就多了2.xml文件,并解析了2.xml
try {
createxml("E:\\2.xml");
                   parserXml("E:\\2.xml");
} catch (Exception e) {
e.printStackTrace();
}
}

}

热点排行