07-06
12

XML的读写操作样例

创建并写入XML:
package xmltest;

import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

public class CreateXML {
    public void Create() {
        try {
            Document doc = new Document();
            ProcessingInstruction pi = new ProcessingInstruction(
                    "xml-stylesheet", "type='text/xsl' href='test.xsl'");
            doc.addContent(pi);

            Element root = new Element("user");
            doc.setRootElement(root);
            Element el1 = new Element("name");

            //Text text1 = new Text("blurxx");
            Element em = new Element("name_last").addContent("blurxx");

            el1.addContent(em);

            Element el2 = new Element("passwd").addContent("1234");

            root.addContent(el1);
            root.addContent(el2);

            //缩进四个空格,自动换行,gb2312编码
            //XMLOutputter outputter = new XMLOutputter("  ", true,"GB2312");
            Format format = Format.getPrettyFormat();
            format.setEncoding("GBK");
            format.setIndent("\t"); //设置分割符
            //format.setNewlines(true);
            XMLOutputter outputter = new XMLOutputter(format);

            outputter.output(doc, new FileWriter("test.xml"));
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String args[]) {
        new CreateXML().Create();
    }

}


XML内容样式:
<?xml version="1.0" encoding="GBK"?>
<?xml-stylesheet type='text/xsl' href='test.xsl'?>
<user>
    <name>
        <name_last>blurxx</name_last>
    </name>
    <passwd>1234</passwd>
</user>


读出XML:
package xmltest;

import java.io.FileInputStream;
import org.jdom.*;
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;

public class LoadXML {
    public static void main(String[] args) throws IOException,
            org.jdom.JDOMException {

        SAXBuilder sb = new SAXBuilder();
        Document doc = null;
        doc = sb.build(new FileInputStream(
                "test.xml"));
        //sb.build(new   FileInputStream("E:\\project\\test.xml")); 也可以用绝对路径
        
        Element user = doc.getRootElement();//读取根
        System.out.println(user.getName()); //取得根名字

        Element name = user.getChild("name"); //读取子集name

        System.out.println(name.getName()); //读取子集name的名字
        System.out.print(name.getChild("name_last").getName());//再读name的子集的名字
        System.out.println(":" + name.getChild("name_last").getValue().toString());//再读name的子集的值

        Element passwd = user.getChild("passwd");
        System.out.print(passwd.getName());
        System.out.println(":" + passwd.getValue());
        user.getChildText("name_last");

    }
}


文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: XML
相关日志:
评论: 0 | 引用: 0 | 查看次数: 656
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭