《通过jdom操作XML.doc》由会员分享,可在线阅读,更多相关《通过jdom操作XML.doc(3页珍藏版)》请在三一文库上搜索。
1、写xmlpackage com.hdz.xml;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;public class TestWriteXml /* * 写XML by jdom * param args */public
2、 static void main(String args) try /输出文件路径String filePath = c:hdz.xml;FileOutputStream out = new FileOutputStream(filePath);/创建根元素Element records = new Element(Records);/设置文档的根元素Document doc = new Document(records);/创建子元素 记录Element record = new Element(Record);/创建子元素内容Element name = new Element(Name
3、);name.setText(管理员);record.addContent(name);Element address = new Element(Address);address.setText(北京);record.addContent(address);record.setAttribute(INDEX, 1);records.addContent(record);records.setAttribute(COUNTS,1);/格式化XMLFormat format = Format.getCompactFormat();format.setEncoding(UTF-8);/设置缩进为4
4、个空格format.setIndent( );/输出XMLXMLOutputter XMLOut = new XMLOutputter(format);XMLOut.output(doc, out);System.out.println(write xml success); catch (FileNotFoundException e) e.printStackTrace(); catch (IOException e) e.printStackTrace();读xmlpackage com.hdz.xml;import java.io.IOException;import java.uti
5、l.Iterator;import java.util.List;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;public class TestReadXml /* * 解析XML by jdom * param args */public static void main(String args) try String filePath = c:hdz.xml;SAXBuilder builder = new SA
6、XBuilder();Document doc = builder.build(filePath);Element root = doc.getRootElement();List records = root.getChildren(Record);for(Iterator it = records.iterator();it.hasNext();)Element element = it.next();List fields = element.getChildren();for(Iterator itFields = fields.iterator();itFields.hasNext();)Element fieldEle = itFields.next();System.out.println(name:+fieldEle.getName()+,value:+fieldEle.getTextTrim(); catch (JDOMException e) / TODO Auto-generated catch blocke.printStackTrace(); catch (IOException e) / TODO Auto-generated catch blocke.printStackTrace();