2015-12-21 84 views
0

我試圖添加前綴到一個標籤代表一個特定的命名空間 - 可以看出以下如何創建帶有命名空間前綴標籤

String envelopePrefix = "omgEnv"; 
      String businessPrefix = "omgBS"; 
      String namespaceURI = "http://www.w3.org/2000/xmlns/"; 

      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 

      Document doc = docBuilder.newDocument(); 
      Element rootElement = doc.createElement("OmgeoMessageContainer"); 

      rootElement.setAttributeNS(namespaceURI, "xmlns:" + envelopePrefix, "http://www.omgeo.com/schema/v1.0/envelope"); 
      rootElement.setAttributeNS(namespaceURI, "xmlns:" + businessPrefix, "http://www.omgeo.com/schema/v1.0/BusinessServices"); 

      doc.appendChild(rootElement); 

      Element messageParties = doc.createElementNS(namespaceURI, envelopePrefix + ":MessageParties"); 
      rootElement.appendChild(messageParties); 

不幸的是我的messageParties元素與下面的錯誤而失敗 -

org.w3c.dom.DOMException中:NAMESPACE_ERR:試圖創建 或在某種程度上這是不正確關於 命名空間改變的對象。

你應該如何給標籤加正確的名稱空間定義?事件setPrefix方法拋出相同的錯誤。

感謝

回答

0

我不認爲你可以決定前綴的名字空間元素而生成XML。我沒有在JavaDocs中看到任何這樣的選項。要使用名稱空間創建元素,應該進行修改。

String namespaceURI = "http://www.w3.org/2000/xmlns/"; 
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 

Document doc = docBuilder.newDocument(); 
Element rootElement = doc.createElementNS(namespaceURI, "OmgeoMessageContainer"); 

doc.appendChild(rootElement); 
Element messageParties = doc.createElementNS(namespaceURI, "MessageParties"); 
rootElement.appendChild(messageParties); 

這將爲命名空間生成具有自動確定前綴的XML。