2016-04-29 22 views
-1

私は、Java Transformer.Theルートノードを使用してXMLファイルを作成していますが、このような構文は次のとおりです。Javaを使用してXMLファイルを作成する方法は?

<AUTO-RESPONSE-DOCUMENT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://someurl">. 

私はこのようなルートノード作成しています:私は上記のURLを入れる必要がありますどのように

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

をAUTO-RESPONSE-DOCUMENTノードの前にありますか?あなたが意味する場合

答えて

0

は、名前空間属性:あなたは他のすべての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); 

この文書をテキストにコードを入れて

 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"/> 
+0

上記のコードは私の問題を修正しました。 –

+0

その場合の回答を受け入れることができます:-) – Jan

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

N "xmlns"の名前空間は、表示されているとおり正確に指定する必要があります。

+0

このアプローチに感謝します。 –

関連する問題