如何使用Java创建xml文件?

时间:2016-04-29 11:57:19

标签: java xml xml-parsing

我正在使用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">.

我正在创建这样的根节点:

Document doc = docBuilder.newDocument();
Element ele = doc.createElement("AUTO-RESPONSE-DOCUMENT");
doc.appendChild(ele);

我应该如何将上述网址放在AUTO-RESPONSE-DOCUMENT节点前面?

2 个答案:

答案 0 :(得分:0)

如果您指的是命名空间属性:您可以像所有其他属性一样设置它们:

        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);

完成此文档到文本代码

        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);

它创建了输出:

<?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"/>

答案 1 :(得分:0)

/**
 * @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));
}

请注意,“xmlns”pefix的命名空间必须完全如图所示。