-- 作者:yanglian2004
-- 发布时间:3/19/2007 4:34:00 PM
-- 用jdom 怎么在xml中写入重复元素
/*例子实现这个xml: <HVTR> <RBIF> <RINM>报告机构名称</RINM> </RBIF> <CATIs> <CATI seqno=”1”> <CTIF> <CTNM>客户名称</CTNM> <CITP>客户身份证件类型</CITP> </CTIF> </CATI> ………(循环CATI) 问题就在这里,做循环时属性值累加,但是元素不变,编译的时候没有问题,运行的时候报错:The Content already has an existing parent "CATI" </CATIs> </HVTR> */ import java.io.*; import org.jdom.*; import org.jdom.input.*; import org.jdom.input.*; import org.jdom.output.*; public class xmlwriter { public void writer() throws IOException,JDOMException { int i=1; Element root,r2,r3,r1,r4,r5; Document Doc; root = new Element("HVTR"); Doc = new Document(root); root.addContent(new Comment("这是注释")); root.addContent(new Element("RBIF").addContent(new Element("RINM").addContent("报告机构名称"))); r1 = new Element("CATIs"); r2 = new Element("CATI"); r3 = new Element("CTIF"); r4 = new Element("CTNM"); r5 = new Element("CITP"); r4.addContent("客户名称"); r5.addContent("客户身份证件类型"); r3.addContent(r4); r3.addContent(r5); for(i=1;i<=10;i++){ String num=Integer.toString(i); r2.addContent(r3).setAttribute("seqno", num); } r1.addContent(r2); root.addContent(r1); Format format = Format.getPrettyFormat(); format.setEncoding("GB2312"); XMLOutputter Outputter = new XMLOutputter(); Outputter.setFormat(format); Outputter.output(Doc, new FileOutputStream("test1.xml")); } public static void main(String[] args) { try { xmlwriter s1 = new xmlwriter(); System.out.println("Now we build an XML document ....."); s1.writer(); } catch (Exception e) { System.out.println(e.getMessage()); } } }
|