遇到一个难题主要是操作命名空间的attribute元素方面。现在需求是下面的XML文件。求助java代码用Dom标准API生成下面XML文件,不用Jdom,Dom4j,Sax哦。
===================================================================
<?xml version="1.0" encoding="UTF-8" ?>
<ns1:MyRequest xmlns:ns1="http://www.namespace1.com" xmlns:ns2="http://www.namespace2.com" ns2:Token="1000">
<ns2:Document xmlns:ns2="http://www.namespace2.com" Archivo="2000" Type="XML"/>
<ns2:Information xmlns:ns2="http://www.namespace2.com" Sender="CN" Receiver="US"/>
<ns1:Addenda Attribute="S" Value="10000" />
</ns1:MyRequest>
====================================================================
谢谢大家拉...
java xml dom
------解决方案--------------------
没看出来哪里难了,网上搜一下应该有demo的,,我写了个可以。。
public void buildXml01(){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//创建一个新的document文档对象,这里返回的document是 org.w3c.dom.Document
Document document = db.newDocument();
//document.setXmlVersion("UTF-8");//默认UTF-8
Element root = document.createElement("ns1:MyRequest");
root.setAttribute("xmlns:ns1", "http://www.namespace1.com");
root.setAttribute("xmlns:ns2", "http://www.namespace2.com");
root.setAttribute("ns2:Token","1000");
Element element01 = document.createElement("ns2:Document");
element01.setAttribute("xmlns:ns2","http://www.namespace2.com");
element01.setAttribute("Archivo","2000");
element01.setAttribute("Type","XML");
Element element02 = document.createElement("ns2:Information");
element02.setAttribute("xmlns:ns2","http://www.namespace2.com");
element02.setAttribute("Sender","CN");
element02.setAttribute("Receiver","US");
Element element03 = document.createElement("ns1:Addenda");
element03.setAttribute("Attribute","S");
element03.setAttribute("value","10000");
document.appendChild(root);//这一步必不可少,绑定父子标签的关联关系
root.appendChild(element01);
root.appendChild(element02);
root.appendChild(element03);
//TransformerFactory这个工厂专门生产Transformer的实例,Transformer实例就可以把封装好的document变成xml格式的文档了
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
//文件写入器
PrintWriter printWriter = new PrintWriter(new FileOutputStream("c:\\server.xml"));
StreamResult result = new StreamResult(printWriter);
//执行写入操作
transformer.transform(source, result);
System.out.println("生成xml文件成功");
printWriter.close();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
http://blog.csdn.net/ch656409110/article/category/1609471