一、前言
通过jdom依赖包将指定xml文件加载解析为字符串文本内容的JAVA代码示例。
二、代码示例
import java.io.File;@b@import java.io.IOException;@b@import java.io.StringWriter;@b@@b@import org.jdom.input.SAXBuilder;@b@import org.jdom.output.Format;@b@import org.jdom.output.XMLOutputter;@b@@b@public class XmlToStringUtil {@b@ @b@ //将xml文件解析为内存文件document@b@ public static org.jdom.Document xml2Document(String filepath){@b@ org.jdom.Document document=null;@b@ try {@b@ SAXBuilder reader = new SAXBuilder(); @b@ document=reader.build(new File(filepath));@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ return document;@b@ }@b@ @b@ //将xml文件解析为字符串@b@ public static String xml2String(String filepath){@b@ org.jdom.Document document=xml2Document(filepath);@b@ Format format =Format.getPrettyFormat(); @b@ format.setEncoding("UTF-8");//设置编码格式 @b@ @b@ StringWriter out=new StringWriter(); //输出对象@b@ XMLOutputter outputter =new XMLOutputter(); @b@ try {@b@ outputter.output(document,out);@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ } @b@ return out.toString();@b@ }@b@ @b@ public static void main(String[] args){@b@ System.out.println(XmlToStringUtil.xml2String("Y:/apache-maven2/maven2/abbot/abbot/0.12.3/abbot-0.12.3.pom"));@b@ }@b@@b@}
控制台打印结果
<?xml version="1.0" encoding="UTF-8"?>@b@<project>@b@ <modelVersion>4.0.0</modelVersion>@b@ <groupId>abbot</groupId>@b@ <artifactId>abbot</artifactId>@b@ <name>Abbot</name>@b@ <version>0.12.3</version>@b@</project>