java中的代码
import java.io.File;
import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
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 CreateXML { public static void main(String[] args) { try {
//创建xml文件。DOM方式
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.newDocument();
//添加根元素,指定标签
Element root=document.createElement("books");
//给根元素添加属性值
root.setAttribute("id", "aaa"); //创建一个子标签
Element book1=document.createElement("book");
book1.setAttribute("id", "1");
//再创建下一级的子标签
Element name1=document.createElement("name");
Element price1=document.createElement("price");
//设定标签内的内容
name1.setTextContent("小说");
price1.setTextContent("100元");
//把子标签添加到上一级标签,appendChild方法
book1.appendChild(name1);
book1.appendChild(price1); //复制以上代码,把节点填充完
Element book2=document.createElement("book");
book2.setAttribute("id", "2");
Element name2=document.createElement("name");
Element price2=document.createElement("price");
name2.setTextContent("杂志");
price2.setTextContent("200元");
book2.appendChild(name2);
book2.appendChild(price2); Element book3=document.createElement("book");
book3.setAttribute("id", "3");
Element name3=document.createElement("name3");
Element price3=document.createElement("price3");
name3.setTextContent("课本");
price3.setTextContent("300元");
book3.appendChild(name3);
book3.appendChild(price3); root.appendChild(book1);
root.appendChild(book2);
root.appendChild(book3);
document.appendChild(root);//最后一步
//文档内容创建完毕,下面是输出文档
TransformerFactory transformerFactory =TransformerFactory.newInstance();
Transformer transformer1=transformerFactory.newTransformer();
StringWriter writer=new StringWriter();
transformer1.transform(new DOMSource(document), new StreamResult(writer));
System.out.println(writer.toString());//成功输出,可以复制
//直接生成xml文件
transformer1.transform(new DOMSource(document), new StreamResult(new File("newxml.xml"))); } catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (TransformerException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} } }
生成的xml文件代码
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books id="aaa">
<book id="1">
<name>小说</name>
<price>100元</price>
</book>
<book id="2">
<name>杂志</name>
<price>200元</price>
</book>
<book id="3">
<name3>课本</name3>
<price3>300元</price3>
</book>
</books>