import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class GeneralXML {
public static void main(String[] args) throws IOException {
//最终生成输出的xml
String xml = "<beans "
+ "xmlns=\"http://www.springframework.org/schema/beans\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\"> "
+ "version=\"1.0\""
+ "<bean id=\"user\" class=\"cn.zlz.User\"> "
+ "<property name=\"sexs\">男</property>" + "</bean>"
+ "</beans> ";
// System.out.println(xml);
Element root = new Element("beans");
Document doc = new Document(root);
//添加第一个声明
Namespace ns = Namespace.getNamespace("","http://www.w3.org/2001/XMLSchema-instance");
//这里使用setNamespace
root.setNamespace(ns);
//添加第二个声明,xsi,第三个的时候需要用
Namespace ns1 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.addNamespaceDeclaration(ns1);
//添加 si:schemaLocation 需要使用第二个声明
root.setAttribute(new Attribute(
"schemaLocation",
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd",
ns1));
//添加属性
root.setAttribute("version", "1.0");
//创建下级节点
Element bean = new Element("bean");
bean.setAttribute("id", "user");
bean.setAttribute("class", "cn.zlz.User");
//这里再添加一次声明,不知道为什么不添加这句,会使root的子节点都会有一个 xlmns = ""的属性。
bean.setNamespace(ns);
Element property = new Element("property");
property.setAttribute("name", "sexs");
//添加属性节点
property.setText("男");
Element bean1 = new Element("bean1");
bean1.setNamespace(ns);
//将节点添加到父节点
bean.addContent(property);
root.addContent(bean);
root.addContent(bean1);
//格式化输出xml文件字符串
Format format = Format.getCompactFormat();
format.setEncoding("utf-8");
//这行保证输出后的xml的格式
format.setIndent(" ");
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream byteRsp = new ByteArrayOutputStream();
xmlout.output(doc, byteRsp);
String str = byteRsp.toString("utf-8");
System.out.println(str);
}
}
使用jdom创建xml文本并格式化输出为字符串xml
最新推荐文章于 2021-03-13 12:28:31 发布