Jdom创建XML 自动换行封装类
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class XMLWriter {
public XMLWriter() {
}
/**
* @param args
*/
public static void main(String[] args) {
//创建节点
Element root = addElement("mobile");
Element el2 = addElement("select");
Element el3_1 = addElement("id");
Element el3_2 = addElement("name");
//赋值
el3_1.addContent("1");
el3_2.addContent("Gql");
//节点从属关系
el2.addContent(el3_1);
el2.addContent(el3_2);
root.addContent(el2);
//创建文件
CreateXml(root,"F:/test.xml");
}
/**
* @param 创建文件
*/
public static void CreateXml(Element rootElement, String Xmlpath) {
// 创建xml文件
Document doc = new Document(rootElement);
XMLOutputter out = new XMLOutputter(" ", true, "GBK");// 设置自动换行,GBK
// XMLOutputter out = newXMLOutputter();//不自动换行的
String xmlStr = out.outputString(doc);
//System.out.println(xmlStr);
try {
out.output(doc, new FileOutputStream(Xmlpath));
} catch (FileNotFoundException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
/**
* @paramm 添加节点Element
* @elementName 节点名字
*/
public static Element addElement(String elementName) {
return new Element(elementName);
}
/**
* @param 添加节点的值
* @element 那个节点
* @value 节点的值
*/
public static void addContent(Element element, String value) {
element.addContent(value);
}
}
联系客服