[英]How to create xml file using Java?
I am creating a xml file using Java Transformer.The root node has syntax like this:我正在使用 Java Transformer 创建一个 xml 文件。根节点的语法如下:
<AUTO-RESPONSE-DOCUMENT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://someurl">.
I am creating the root node like this:我正在创建这样的根节点:
Document doc = docBuilder.newDocument();
Element ele = doc.createElement("AUTO-RESPONSE-DOCUMENT");
doc.appendChild(ele);
How should i put the above urls in front of AUTO-RESPONSE-DOCUMENT node?我应该如何将上述网址放在 AUTO-RESPONSE-DOCUMENT 节点前面?
If you mean the namespace attributes: You can set them like all other atributes:如果您的意思是命名空间属性:您可以像所有其他属性一样设置它们:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element ele = doc.createElement("AUTO-RESPONSE-DOCUMENT");
//Add namespace attibutes
ele.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
ele.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
ele.setAttribute("xmlns", "http://someurl");
doc.appendChild(ele);
Put through this Document-To-Text code输入此 Document-To-Text 代码
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
It creates that output:它创建该输出:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<AUTO-RESPONSE-DOCUMENT xmlns="http://someurl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
/**
* @param args
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws Exception {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element ele = doc.createElement("AUTO-RESPONSE-DOCUMENT");
doc.appendChild(ele);
ele.setAttribute("xmlns", "http://someurl");
ele.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
ele.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(System.out));
}
Note the namespace for "xmlns" pefix must be exactly as shown.请注意,“xmlns”pefix 的命名空间必须完全如图所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.