2011-06-16 129 views
0

在創建XML作爲RMI程序的節點的過程中,我正在開發,但是我遇到了一個問題。我可以使用DOM創建XML,但我很努力地將命名空間和版本添加到我的XML的頂部。我已經嘗試過使用setAttribute和setAttributeNS,但是此刻我失去了我能做的事情。Java DOM,命名空間/版本問題

Java代碼來創建元素是:

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); 
      Document doc = docBuilder.newDocument(); 

      Node root = doc.createElement("Request"); 
      doc.appendChild(root); 

//code ommited 

結果我得到現在是:

<Request> 
    <Identification> 
     <UserID>user</UserID> 
     <Password>pass</Password> 
    </Identification> 
</Request> 

在請求部分,我需要它看起來像:

<Request xsi:noNamespaceSchemaLocation="URL" Version="1.0"> 

任何幫助將不勝感激,以幫助解決這個問題!

感謝

+0

類似的問題[這裏](http://stackoverflow.com/questions/1492428/javadom-how-do-i-set-the-base-namespace-of-an-already-created-document) – talnicolas 2011-06-16 12:38:05

回答

1

我想你想要的東西,如:

... 
Element root = doc.createElement("Request"); 
root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation", "URL"); 
root.setAttribute("Version", "1.0"); 
doc.appendChild(root); 
... 

定義root作爲Element給你.setAttribute *方法。

這將使你

<Request Version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="URL"/> 

我知道,包括多一點,但XMLNS:需要XSI屬性,這樣XSI命名空間中定義。

+0

謝謝,這是我之前嘗試的,而不是元素根,我使用的是拋出錯誤的節點根。現在有道理! – Sad 2011-06-16 13:28:13