欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Jdom 生成和解析XML字符串

程序员文章站 2022-05-28 10:38:54
...

//生成XML字符串

package com.abin.xml;

import java.io.ByteArrayOutputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class CreateXML {

public static String Create(){
Element root=new Element("people");
Document doc=new Document(root);

for(int i=0;i<5;i++){
Element element=new Element("user");
element.setAttribute("id", ""+""+i);

element.addContent(new Element("name").setText("abin"+i));
element.addContent(new Element("age").setText("1"+i));
element.addContent(new Element("sex").setText("female"+i));

root.addContent(element);
}
ByteArrayOutputStream byteRsp=new ByteArrayOutputStream();
XMLOutputter xmlOut=new XMLOutputter();
try {
xmlOut.output(doc, byteRsp);
} catch (Exception e) {
e.printStackTrace();
}

return byteRsp.toString();
}

public static void main(String[] args) {
CreateXML xml=new CreateXML();
String result=xml.Create();
System.out.println("result="+result);
}

}






//解析XML字符串

package com.abin.xml;

import java.io.StringReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class ParseXML {

public static void Parse(String xml){
//创建一个新的字符串
StringReader reader=new StringReader(xml);
InputSource source=new InputSource(reader);
SAXBuilder sax=new SAXBuilder();

try {
Document doc=sax.build(source);
Element root=doc.getRootElement();
System.out.println("root's name="+root.getName());
System.out.println("root's value="+root.getValue());

List node=root.getChildren();
Element el=null;
for(int i=0;i<node.size();i++){
el=(Element)node.get(i);
System.out.println("el's name="+el.getName());
System.out.println("el's value="+el.getValue());
List node1=el.getChildren();
Element el1=null;
for(int j=0;j<node1.size();j++){
el1=(Element)node1.get(j);
System.out.println("el1's name="+el1.getName());
System.out.println("el1's value="+el1.getValue());
}
}

} catch (Exception e) {
e.printStackTrace();
}

}


}






//Junit测试XML

package com.abin.xml;

import org.junit.Before;
import org.junit.Test;

public class UseXML {
CreateXML create=null;
ParseXML parse=null;

@Before
public void setUp(){
create=new CreateXML();
parse=new ParseXML();
}

@Test
public void test(){
String result=create.Create();
System.out.println("生成的XML字符串是:"+result);
parse.Parse(result);
}


}



相关标签: jdom xml