java生成xml文件(转)

jdom下载   http://jdom.org/这里有最新的jdom下载。
安装配置

//=====================java 生成 xml
//----生成的xml在工程目录下---

//-----java文件------
package javaapplication2;
import   java.io.*;
import   org.jdom.*;
import   org.jdom.input.*;
import   org.jdom.input.*;
import   org.jdom.output.*;
public   class   test1 {
    public   void   BuildXMLDoc()   throws   IOException,   JDOMException {
        Element   eeeRoot,   eee1,   eee2;
        Document   Doc;
        eeeRoot   =   new   Element("employees_information");
        Doc   =   new   Document(eeeRoot);
        eeeRoot   =   Doc.getRootElement();
        eee1   =   new   Element("name");
        eee2   =   eee1.setText("C.Y.   Shen");
        //eee2   =   eee1.addAttribute("emp_id",   "001");
        eee1   =   eeeRoot.addContent(eee2);
        eee1   =   new   Element("age");
        eee2   =   eee1.setText("43");
        eee1   =   eeeRoot.addContent(eee2);
        eee1   =   new   Element("sex");
        eee2   =   eee1.setText("Male");
        eee1   =   eeeRoot.addContent(eee2);
        //   XMLOut.setEncoding("gb2312");
        XMLOutputter   XMLOut   =   new   XMLOutputter();
        XMLOut.output(Doc,   new   FileOutputStream("test1.xml"));
    }
    public   static   void   main(String[]   args) {
        try   {
            test1   s1   =   new   test1();
            System.out.println("Now   we   build   an   XML   document   .....");
            s1.BuildXMLDoc();
        } catch   (Exception   e) {
            System.out.println(e.getMessage());
        }
    }
}
//========生成的xml文件=============
<?xml version="1.0" encoding="UTF-8"?>
<employees_information><name>C.Y.   Shen</name><age>43</age><sex>Male</sex></employees_information>
++++++++++++++++++++++++++++++++++++++++++++++++++++++

生成一个xml文件,包括雇员信息,文件个数。。最关键的是包括一个图片的二进制流信息,注意要去www.jdom.org下载jdom包,并加入classpath中
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class test1 {
ReadBase64Pic pic=new ReadBase64Pic();
String basestr=null;
public void BuildXMLDoc() throws IOException, JDOMException
{       
   Element eeeRoot, eee1, eee2;
   Document Doc;
   eeeRoot = new Element("employees_information");
   Doc = new Document(eeeRoot);
   eeeRoot = Doc.getRootElement();
   eee1 = new Element("FileCount");
   eee2 = eee1.setText("3");        //eee2 = eee1.addAttribute("emp_id", "001");
   eee1 = eeeRoot.addContent(eee2);

   eee1 = new Element("ToID");
   eee2 = eee1.setText("13910381217");
   eee1 = eeeRoot.addContent(eee2);
  
       
   eee1 = eeeRoot.addContent(eee2);
   basestr=pic.Read();
   eee1 = new Element("File");
   eee1=eee1.setAttribute("Name","13910381217.smil");
   eee1=eee1.setAttribute("Number","1");
   eee2 = eee1.setText(basestr);
   eee1 = eeeRoot.addContent(eee2);


  
   XMLOutputter XMLOut = new XMLOutputter();
   //XMLOut.setEncoding("gb2312");
   XMLOut.output(Doc, new FileOutputStream("mms.xml"));
}
public static void main(String[] args) {
   try {
   
    test1 s1 = new test1();
    System.out.println("Now we build an XML document .....");
    s1.BuildXMLDoc();
       }
   catch (Exception e)
   {
    System.out.println(e.getMessage());
   }
}
}
生成的文件如下 test.xml
<?xml version="1.0" encoding="UTF-8"?>
<employees_information>
<FileCount>3</FileCount>
<FromID>8850104</FromID>
<FeeID>13910381217</FeeID>
<Title>TWINFCH</Title>
<Province>6010</Province>
<File Name="13910381217.smil" Number="1">
R0lGODlhZQBQAD8AANx5ST+8oj/RuuWXevOYZz/DrQoBAT/LxT/Uy8RZONeHaf6zPz/Lsz/Muth4&#xD;
V9hjOtZpQuR3SP6zjO2TaLdVOD+6nD/YzP29PzkWFj83Kv7EPz8/P0UaGT/h1f61Pz/u6uqkPz/w&#xD;
......
......
......
CKOBKVzzxhs/BQochKcSPyVPBtCzABu1ZzM/Pz9U6nOf5DRpOT80UIHWcqBTPynRarLFIdyjA3ZC&#xD;
n33YYjZ4ypOJQiUCEQJgz7x49JlJPyY1noEOPwUEADs=
</File>
</employees_information>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
用java生成XML的例子
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
public class writexml{
private Document document;
private String filename;

public writexml(String name) throws ParserConfigurationException{
filename=name;
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
document=builder.newDocument();
}
public void toWrite(String mytitle,String mycontent){
Element root=document.createElement("WorkShop");
document.appendChild(root);
Element title=document.createElement("Title");
title.appendChild(document.createTextNode(mytitle));
root.appendChild(title);
Element content=document.createElement("Content");
content.appendChild(document.createTextNode(mycontent));
root.appendChild(content);

}
public void toSave(){
try{
TransformerFactory tf=TransformerFactory.newInstance();
Transformer transformer=tf.newTransformer();
DOMSource source=new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING,"GB2312");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
PrintWriter pw=new PrintWriter(new FileOutputStream(filename));
StreamResult result=new StreamResult(pw);
transformer.transform(source,result);
}
catch(TransformerException mye){
mye.printStackTrace();
}
catch(IOException exp){
exp.printStackTrace();
}
}
public static void main(String args[]){
try{
writexml myxml=new writexml("d://9.xml");
myxml.toWrite("中文题目","中文内容");
myxml.toSave();
System.out.print("Your writing is successful!");
}
catch(ParserConfigurationException exp){
exp.printStackTrace();
System.out.print("Your writing is failed!");
}
}
}     

dom4j read xml
package com.scjp;

import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.Node;


public class ParserXmlDom4j
{
public final static String filePath = "com//scjp//MyXml.xml";

public Document parse(File file) throws DocumentException
{
SAXReader reader = new SAXReader();
Document document = reader.read(file);

return document;
}

public void getXml(Document document) throws DocumentException
{
Element root = document.getRootElement();
Iterator it = root.elementIterator();

//Iterator it = root.elementIterator("name");
//Iterator it = root.attributeIterator();
while (it.hasNext())
{
Element sub = (Element) it.next();
}
}

public void getNode(Document document) throws DocumentException
{
//List list = document.selectNodes("//row/person");
Node node = document.selectSingleNode("//row/person/name");
String value = node.getText();
System.out.println("value : " + value);
}

public void writeXml() throws Exception
{
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
root.addComment("this is test xml file");
ArrayList children = new ArrayList();
Element ele1 = root.addElement("element1");
ele1.addAttribute("attr1","a");
ele1.addAttribute("attr2","b");
ele1.setText("this is element1");
Element ele2 = root.addElement("element2");
ele2.addAttribute("attr21","c");
ele2.setText("this is element2");

XMLWriter writer = null;
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(new FileWriter(new File("com//scjp//MyXml3.xml")),format);
writer.write(doc);
writer.close();


}

public static void main(String[] args)
{
ParserXmlDom4j pxd = new ParserXmlDom4j();

try
{

File file = new File(filePath);
Document document = pxd.parse(file);


Element root = document.getRootElement();
List list = root.selectNodes("//root/standards");
for(Iterator it = list.iterator();it.hasNext();)
{
Element subElement = (Element)it.next();
Attribute subAttr = subElement.attribute("type");
if("a3".equals(subAttr.getValue()))
{
for(Iterator ita = subElement.elementIterator("standard");ita.hasNext();)
{
Element belement = (Element)ita.next();
String sno = belement.attributeValue("sno");
System.out.println("sno : "+sno );
}
/*
List a3List = subElement.selectNodes("/@sno");
for(Iterator it3 = a3List.iterator();it3.hasNext();)
{
Attribute attr3 = (Attribute)it3.next();
String novalue = attr3.getValue();
System.out.println("novalue : "+ novalue);
}
*/
}
}

pxd.writeXml();
/*
List list = root.selectNodes("//root/standards/standard/@sno");
for(int i=0; i<list.size(); i++)
{
Attribute attrs = (Attribute)list.get(i);
String no = attrs.getValue();
System.out.println("no value : "+ no);
}
*/
/*
for(Iterator it = root.elementIterator("author"); it.hasNext();)
{
Element sub = (Element)it.next();
String name = sub.attributeValue("name");
String location = sub.attributeValue("location");
String fulName = sub.getText();
System.out.println("name "+name+" location : "+ location+" fulName "+ fulName);
}
*/
//pxd.getNode(doc);
//SAXReader reader = new SAXReader();
//Document document = reader.read(filePath);
/*
List list = document.selectNodes("//c/a/b/@color");

for (Iterator iter = list.iterator(); iter.hasNext();)
{
Attribute attribute = (Attribute) iter.next();
String color = attribute.getValue();
System.out.println("color : "+ color);
if (color.equals("255.255.0"))
{
attribute.setValue("0.0.0");
}
}
*/

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

<?xml version="1.0" encoding="UTF-8"?>

<!--
<xml-body>
<config>
<font>
<name>HanZi</name>
<size unit="pt">36</size>

</config>
</xml-body>

<row>
<person>
<name>王小明</name>
<college>信息学院</college>
<telephone>6258113</telephone>
<notes>男,1955年生,博士,95年调入海南大学</notes>
</person>
</row>

<c>
<a name="a">
<b color="255.255.0"/>

<a name="b">
<b color="255.255.1"/>

</c>

<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US">Bob McWhirter</author>
</root>
-->

<standards type="a3">
<standard sno="1" svalue="400" />
<standard sno="3" svalue="400" />
</standards>
<standards type="b9">
<standard sno="1" svalue="300" />
</standards>  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值