jdom 对xml的操作

package com.linzl.cn.xml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.jdom2.Attribute;
import org.jdom2.CDATA;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
import org.xml.sax.InputSource;

/**
* 依赖 jdom-2.0.5.jar
*
* @author linzl 最后修改时间:2014年10月10日
*/
public class JdomUtils {
private static final String DEFAULT_CHARSET = “GBK”;

/**
 * 使用JDK自带的类转换Document对象转成字符串
 * 
 * @param doc
 * @return
 * @throws TransformerException
 */
public static String docToString(Document doc) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty("encoding", DEFAULT_CHARSET);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    transformer.transform(new JDOMSource(doc), new StreamResult(bos));
    return bos.toString();
}

/**
 * xml文件转Document
 * 
 * @param file
 * @return
 * @throws JDOMException
 * @throws IOException
 */
public static Document fileToDoc(File file) throws JDOMException,
        IOException {
    SAXBuilder sax = new SAXBuilder();
    Document doc = sax.build(file);
    return doc;
}

/**
 * xml文件转Document
 * 
 * @param file
 * @return
 * @throws JDOMException
 * @throws IOException
 */
public static Document fileToDoc(InputStream is) throws JDOMException,
        IOException {
    SAXBuilder sax = new SAXBuilder();
    Document doc = sax.build(is);
    return doc;
}

/**
 * xml文件转Document
 * 
 * @param file
 * @return
 * @throws JDOMException
 * @throws IOException
 */
public static Document fileToDoc(String pathName, String charset)
        throws JDOMException, IOException {
    SAXBuilder sax = new SAXBuilder();
    InputStream is = new FileInputStream(pathName);
    charset = (charset == null || charset.trim().length() <= 0) ? DEFAULT_CHARSET
            : charset;
    InputStreamReader isr = new InputStreamReader(is, charset);
    Document doc = sax.build(is);
    return doc;
}

/**
 * 字符串内容转换成Document对象
 * 
 * @param xmlStr
 * @return
 * @throws JDOMException
 * @throws IOException
 */
public static Document stringToDoc(String xmlStr) throws JDOMException,
        IOException {
    StringReader sr = new StringReader(xmlStr);
    InputSource is = new InputSource(sr);
    Document doc = (new SAXBuilder()).build(is);
    return doc;
}

/**
 * Document对象格式化成字符串
 * 
 * @param doc
 * @return
 * @throws IOException
 */
public static String formatDocToString(Document doc) throws IOException {
    Format format = Format.getPrettyFormat();
    format.setEncoding(DEFAULT_CHARSET);// 设置xml文件的字符为UTF-8,解决中文问题

    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    XMLOutputter xmlout = new XMLOutputter(format);
    xmlout.output(doc, bo);
    return bo.toString();
}

/**
 * 将Document对象格式化到目标文件
 * 
 * @param doc
 * @param targetFile
 * @throws IOException
 */
public static void formatToXMLFile(Document doc, File targetFile)
        throws IOException {
    Format format = Format.getPrettyFormat();
    format.setEncoding(DEFAULT_CHARSET);// 设置xml文件的字符为UTF-8,解决中文问题

    OutputStream os = new FileOutputStream(targetFile);
    XMLOutputter xmlout = new XMLOutputter(format);
    xmlout.output(doc, os);
}

/**
 * 将xmlStr格式化输出到目标文件
 * 
 * @param xmlStr
 * @param targetFile
 * @throws JDOMException
 * @throws IOException
 */
public static void formatToXMLFile(String xmlStr, File targetFile)
        throws JDOMException, IOException {
    Document doc = stringToDoc(xmlStr);
    formatToXMLFile(doc, targetFile);
}

/**
 * 将xml文件格式化输出到目标文件
 * 
 * @param srcFile
 *            xml源文件
 * @param targetFile
 *            格式化输出xml文件
 * @throws JDOMException
 * @throws IOException
 */
public static void formatToXMLFile(File srcFile, File targetFile)
        throws JDOMException, IOException {
    Document doc = fileToDoc(srcFile);
    formatToXMLFile(doc, targetFile);
}

/**
 * 打印Document的结点基本信息
 * 
 * @param doc
 */
public static void printNode(Document doc) {
    Element root = doc.getRootElement();
    printRecursive(root);
}

/**
 * 递归打印结点信息
 * 
 * @param element
 */
private static void printRecursive(Element element) {
    List<Attribute> attr = element.getAttributes();
    // 遍历属性节点
    for (Attribute attribute : attr) {
        System.out.println("结点" + element.getName() + "--》属性"
                + attribute.getName() + ":" + attribute.getValue());
    }

    List<Element> nodeList = element.getChildren();

    for (Element child : nodeList) {
        System.out.println("结点名称:" + child.getName().trim());
        System.out.println("结点值:" + child.getValue().trim());
        printRecursive(child);
    }
}

public static void createDocXML() throws IOException {

    Element root = new Element("root");
    Comment comment = new Comment("根结点注释");
    root.addContent(comment);

    Element rootChildA = new Element("rootChildA");
    rootChildA.addContent("rootChildA孩子结点");
    rootChildA.setAttribute("name", "姓名");
    rootChildA.setAttribute("age", "年龄");
    rootChildA.setAttribute("height", "身高");
    root.addContent(rootChildA);

    Element rootChildB = new Element("rootChildB");
    rootChildB.addContent(new CDATA("rootChildB孩子结点"));
    root.addContent(rootChildB);

    Document doc = new Document();
    doc.addContent(root);

    Format format = Format.getPrettyFormat();
    // format.setIndent("");// 设置换行
    format.setEncoding(DEFAULT_CHARSET);// 设置xml文件的字符为UTF-8,解决中文问题

    OutputStream os = new FileOutputStream(new File("D:\\jdom.xml"));
    XMLOutputter xmlout = new XMLOutputter(format);
    xmlout.output(doc, os);
}

public static void deleteNode() {

}

public static void updateNode() {

}

public static void main(String[] args) throws Exception {
    InputStream is = JdomUtils.class
            .getResourceAsStream("/com/linzl/cn/xml/xmlRead.xml");

    is = JdomUtils.class.getClassLoader().getResourceAsStream(
            "com/linzl/cn/xml/xmlRead.xml");
    Document doc = fileToDoc(is);

    printNode(doc);

// createDocXML();
}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值