2011-12-02 133 views
6

我正在嘗試使用最新的JDOM包生成XML文檔。我遇到了根元素和名稱空間的問題。我需要生產這根元素:JDOM中的名稱空間(默認)

<ManageBuildingsRequest 
    xmlns="http://www.energystar.gov/manageBldgs/req" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.energystar.gov/manageBldgs/req 
         http://estar8.energystar.gov/ESES/ABS20/Schemas/ManageBuildingsRequest.xsd"> 

我用這個代碼:

Element root = new Element("ManageBuildingsRequest"); 
root.setNamespace(Namespace.getNamespace("http://www.energystar.gov/manageBldgs/req")); 
Namespace XSI = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 
root.addNamespaceDeclaration(XSI); 
root.setAttribute("schemaLocation", "http://www.energystar.gov/manageBldgs/req http://estar8.energystar.gov/ESES/ABS20/Schemas/ManageBuildingsRequest.xsd", XSI); 

Element customer = new Element("customer"); 
root.addContent(customer); 
doc.addContent(root); // doc jdom Document 

然而,ManageBuildingsRequest後的下一個元素都有默認的命名空間爲好,它打破了驗證:

<customer xmlns=""> 

任何幫助?感謝您的時間。

+0

你能後的代碼生成您的XML嗎? – GETah

回答

15

您用於customer元素的constructor創建時沒有名稱空間。您應該使用Namespace作爲參數的構造函數。您也可以爲根和客戶元素重用相同的Namespace對象。

Namespace namespace = Namespace.getNamespace("http://www.energystar.gov/manageBldgs/req"); 
Element root = new Element("ManageBuildingsRequest", namespace); 
Namespace XSI = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 
root.addNamespaceDeclaration(XSI); 
root.setAttribute("schemaLocation", "http://www.energystar.gov/manageBldgs/req http://estar8.energystar.gov/ESES/ABS20/Schemas/ManageBuildingsRequest.xsd", XSI); 

Element customer = new Element("customer", namespace); 
root.addContent(customer); 
doc.addContent(root); // doc jdom Document 
+2

你說得對,但我不太清楚爲什麼。我必須將名稱空間傳遞給我有很多的每個孩子 - 變得非常痛苦,但是這固定了它。謝謝。 – jn1kk

+0

@jsn進入相同的問題,並完全同意你的看法。這是一個糟糕的API。希望找到更好的解決方案。 –

1

下面是實現一個跳過發射空的命名空間聲明定製XMLOutputProcessor一個替代的方法:

public class CustomXMLOutputProcessor extends AbstractXMLOutputProcessor { 
    protected void printNamespace(Writer out, FormatStack fstack, Namespace ns) 
      throws java.io.IOException { 
     System.out.println("namespace is " + ns); 
     if (ns == Namespace.NO_NAMESPACE) { 
      System.out.println("refusing to print empty namespace"); 
      return; 
     } else { 
      super.printNamespace(out, fstack, ns); 
     } 
    } 
} 
+0

這篇文章可能比較老,但這對於一個陷入困境的API來說是一個相當優雅的解決方法。謝謝! – Didjit

0

我試圖javanna的代碼,但不幸的是它保留在生成的文檔的內容的空命名空間。在嘗試了bearontheroof的代碼之後,XML導出得很好。

你必須創建自定義類後,做這樣的事情:

CustomXMLOutputProcessor output = new CustomXMLOutputProcessor(); 
output.process(new FileWriter("/path/to/folder/generatedXML.xml"), Format.getPrettyFormat(), document); 
相關問題