如何用java生成一个xml文件
如何用JAVA生成一个XML文件,XML文件内容是字符串X的内容。还请高人说下实现的步骤、要点。有事例代码更好。...
如何用JAVA 生成一个XML文件,XML文件内容是字符串X的内容。还请高人说下实现的步骤、要点。有事例代码更好。
展开
3个回答
2015-08-08 · 知道合伙人数码行家
关注
展开全部
一个XML文档,可以先构造一个DOM,然后将DOM转化为xml序列,输出或者生成文件。package test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Test {
public static void generate(){
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlVersion("1.0");
document.setXmlStandalone(true);
Element root = document.createElement_x("MobileNet"); //创建根节点
document.appendChild(root); //将根节点添加到Document对象中
Element pageElement = document.createElement_x("page"); //设置第一个page元素到
pageElement.setAttribute("name", "list.jsp"); //设置page节点的name属性
Element methodElement = document.createElement_x("method"); //设置method节点
methodElement.setTextContent("get"); //给method设置值
pageElement.appendChild(methodElement); //添加method节点到page节点内
Element displayElement = document.createElement_x("display"); //设置method节点
displayElement.setTextContent("list撒旦发放"); //给display设置值
pageElement.appendChild(displayElement); //添加display节点到page节点内
Element request_paramElement = document.createElement_x("request_param");
request_paramElement.setTextContent("request_param1|request_param2");
pageElement.appendChild(request_paramElement);
root.appendChild(pageElement);
pageElement = document.createElement_x("page"); //设置第二个page元素到
pageElement.setAttribute("name", "content.jsp"); //设置page节点的name属性
methodElement = document.createElement_x("method");
methodElement.setTextContent("post");
pageElement.appendChild(methodElement);
displayElement = document.createElement_x("display");
displayElement.setTextContent("content");
pageElement.appendChild(displayElement);
Element url_titleElement = document.createElement_x("url_title"); //设置url_title节点
url_titleElement.setTextContent("title,publisher,published_calendar"); //给url_title设置值
pageElement.appendChild(url_titleElement); //添加url_title节点到page节点内
root.appendChild(pageElement); //将page段加人根节点内
TransformerFactory transFactory = TransformerFactory.newInstance(); //开始把Document映射到文件
Transformer transFormer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(document); //设置输出结果
File file = new File("MobileNetRule.xml"); //生成xml文件
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file); //文件输出流
StreamResult xmlResult = new StreamResult(out); //设置输入源
transFormer.transform(domSource, xmlResult); //输出xml文件
System.out.println(file.getAbsolutePath()); //测试文件输出的路径
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{/encoding/}","GB2312/");
ByteArrayOutputStream boc = new ByteArrayOutputStream();
t.transform(new DOMSource(document), new StreamResult(boc));
String xmlstring = boc.toString();
System.out.println(xmlstring);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
Test.generate();
}
}
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Test {
public static void generate(){
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlVersion("1.0");
document.setXmlStandalone(true);
Element root = document.createElement_x("MobileNet"); //创建根节点
document.appendChild(root); //将根节点添加到Document对象中
Element pageElement = document.createElement_x("page"); //设置第一个page元素到
pageElement.setAttribute("name", "list.jsp"); //设置page节点的name属性
Element methodElement = document.createElement_x("method"); //设置method节点
methodElement.setTextContent("get"); //给method设置值
pageElement.appendChild(methodElement); //添加method节点到page节点内
Element displayElement = document.createElement_x("display"); //设置method节点
displayElement.setTextContent("list撒旦发放"); //给display设置值
pageElement.appendChild(displayElement); //添加display节点到page节点内
Element request_paramElement = document.createElement_x("request_param");
request_paramElement.setTextContent("request_param1|request_param2");
pageElement.appendChild(request_paramElement);
root.appendChild(pageElement);
pageElement = document.createElement_x("page"); //设置第二个page元素到
pageElement.setAttribute("name", "content.jsp"); //设置page节点的name属性
methodElement = document.createElement_x("method");
methodElement.setTextContent("post");
pageElement.appendChild(methodElement);
displayElement = document.createElement_x("display");
displayElement.setTextContent("content");
pageElement.appendChild(displayElement);
Element url_titleElement = document.createElement_x("url_title"); //设置url_title节点
url_titleElement.setTextContent("title,publisher,published_calendar"); //给url_title设置值
pageElement.appendChild(url_titleElement); //添加url_title节点到page节点内
root.appendChild(pageElement); //将page段加人根节点内
TransformerFactory transFactory = TransformerFactory.newInstance(); //开始把Document映射到文件
Transformer transFormer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(document); //设置输出结果
File file = new File("MobileNetRule.xml"); //生成xml文件
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file); //文件输出流
StreamResult xmlResult = new StreamResult(out); //设置输入源
transFormer.transform(domSource, xmlResult); //输出xml文件
System.out.println(file.getAbsolutePath()); //测试文件输出的路径
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{/encoding/}","GB2312/");
ByteArrayOutputStream boc = new ByteArrayOutputStream();
t.transform(new DOMSource(document), new StreamResult(boc));
String xmlstring = boc.toString();
System.out.println(xmlstring);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
Test.generate();
}
}
展开全部
//首先下载并添加dom4j.jar包(自己下载)
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @author wsj
*/
public class Test1 {
public static void main(String[] args) throws Exception {
Document dom=DocumentHelper.createDocument();//创建xml文件
Element root=dom.addElement("XVal");//添加根元素,Xval
root.addAttribute("X", "X字符串的值");
root.setText("Xval标签中间的值");
String xml=dom.asXML();
System.out.println(xml);
File f=new File("d:/xml.xml");
PrintWriter pw=new PrintWriter(f);
pw.write(xml);
pw.close();
JOptionPane.showMessageDialog(null, "已生成xml文件,路径为为d:/xml.xml");
}
}
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @author wsj
*/
public class Test1 {
public static void main(String[] args) throws Exception {
Document dom=DocumentHelper.createDocument();//创建xml文件
Element root=dom.addElement("XVal");//添加根元素,Xval
root.addAttribute("X", "X字符串的值");
root.setText("Xval标签中间的值");
String xml=dom.asXML();
System.out.println(xml);
File f=new File("d:/xml.xml");
PrintWriter pw=new PrintWriter(f);
pw.write(xml);
pw.close();
JOptionPane.showMessageDialog(null, "已生成xml文件,路径为为d:/xml.xml");
}
}
参考资料: 还有其他问题的话,给我发百度消息
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
dom4j,你需要我可以发给你!
我这有~
小例子
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*新建一个myXML文件在目录下:内容如下
*<hibernate-mapping>
* <class name="com.aptech.User" table="t_user">
* <property name="username"></property>
* <property name="password"></property>
* </class>
*</hibernate-mapping>
*
*/
public class Dom4j {
public static void main(String[] args)throws Exception {
System.out.println("=========readerXML=========");
readerXML();
System.out.println("\n\n\n=========readerXMLNodes=========");
readXMLNodes();
System.err.println("\n\n===========readerXMLChild==========");
readerXMLChild();
System.err.println("\n\n============= making end ......====================");
makeXML();
}
/**
* 得到子节点3种办法1.如下 2.迭代器(iterate)
* @throws Exception
*/
public static void readerXML() throws Exception{
//实例化SAXReader DOM4J核心对象
SAXReader reader=new SAXReader();
//得到document解析文件
Document document=reader.read(new File("myxml.xml"));
//得到文件节点名称
Element element=document.getRootElement();
//输出文件节点名称
System.out.println(element.getName());
}
public static void readXMLNodes() throws Exception{
SAXReader reader =new SAXReader();
Document document = reader.read(new File("myxml.xml"));
Element element=document.getRootElement();
for (Iterator i= element.elementIterator();i.hasNext();) {
Element nextElement=(Element)i.next();
System.out.println(nextElement.getName());
for (Iterator j = nextElement.attributeIterator();j.hasNext();) {
Attribute attribute=(Attribute)j.next();
System.out.println((attribute.getName()+"----"+attribute.getValue()));
}
}
}
/**
* 从指定的节点读取属性及值
* @throws Exception
*/
public static void readerXMLChild() throws Exception{
SAXReader reader =new SAXReader();
Document document=reader.read(new File("myxml.xml"));
List<Node> list = document.selectNodes("//hibernate-mapping/class/property");//找到指定节点
for (Node n:list) {
System.out.print(n.getName()+"===>");
System.out.println(n.valueOf("@name"));
}
}
/**
* 制作XML文件
* @throws Exception
*/
public static void makeXML()throws Exception{
//得到document对象
Document document =DocumentHelper.createDocument();
//添加根节点
Element root=document.addElement("hibernate-mapping");
//添加节点class,属性名为name与table 分别赋值
Element classElement=root.addElement("class")
.addAttribute("name","com.aptech.User").
addAttribute("table", "t_user");//addText 节点里的文本
//添加property子节点,添加属性name 值为"username"
classElement.addElement("property").addAttribute("name","username");
//格式化输出文件
OutputFormat format=OutputFormat.createPrettyPrint();
//声明写出文件
XMLWriter writer=new XMLWriter(new FileWriter("User2.xml"),format);
//写出文件
writer.write(document);
//关闭文件流
writer.close();
}
}
我这有~
小例子
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*新建一个myXML文件在目录下:内容如下
*<hibernate-mapping>
* <class name="com.aptech.User" table="t_user">
* <property name="username"></property>
* <property name="password"></property>
* </class>
*</hibernate-mapping>
*
*/
public class Dom4j {
public static void main(String[] args)throws Exception {
System.out.println("=========readerXML=========");
readerXML();
System.out.println("\n\n\n=========readerXMLNodes=========");
readXMLNodes();
System.err.println("\n\n===========readerXMLChild==========");
readerXMLChild();
System.err.println("\n\n============= making end ......====================");
makeXML();
}
/**
* 得到子节点3种办法1.如下 2.迭代器(iterate)
* @throws Exception
*/
public static void readerXML() throws Exception{
//实例化SAXReader DOM4J核心对象
SAXReader reader=new SAXReader();
//得到document解析文件
Document document=reader.read(new File("myxml.xml"));
//得到文件节点名称
Element element=document.getRootElement();
//输出文件节点名称
System.out.println(element.getName());
}
public static void readXMLNodes() throws Exception{
SAXReader reader =new SAXReader();
Document document = reader.read(new File("myxml.xml"));
Element element=document.getRootElement();
for (Iterator i= element.elementIterator();i.hasNext();) {
Element nextElement=(Element)i.next();
System.out.println(nextElement.getName());
for (Iterator j = nextElement.attributeIterator();j.hasNext();) {
Attribute attribute=(Attribute)j.next();
System.out.println((attribute.getName()+"----"+attribute.getValue()));
}
}
}
/**
* 从指定的节点读取属性及值
* @throws Exception
*/
public static void readerXMLChild() throws Exception{
SAXReader reader =new SAXReader();
Document document=reader.read(new File("myxml.xml"));
List<Node> list = document.selectNodes("//hibernate-mapping/class/property");//找到指定节点
for (Node n:list) {
System.out.print(n.getName()+"===>");
System.out.println(n.valueOf("@name"));
}
}
/**
* 制作XML文件
* @throws Exception
*/
public static void makeXML()throws Exception{
//得到document对象
Document document =DocumentHelper.createDocument();
//添加根节点
Element root=document.addElement("hibernate-mapping");
//添加节点class,属性名为name与table 分别赋值
Element classElement=root.addElement("class")
.addAttribute("name","com.aptech.User").
addAttribute("table", "t_user");//addText 节点里的文本
//添加property子节点,添加属性name 值为"username"
classElement.addElement("property").addAttribute("name","username");
//格式化输出文件
OutputFormat format=OutputFormat.createPrettyPrint();
//声明写出文件
XMLWriter writer=new XMLWriter(new FileWriter("User2.xml"),format);
//写出文件
writer.write(document);
//关闭文件流
writer.close();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询