2011-12-02 7 views
6

最新のJDOMパッケージを使用してXML文書を作成しようとしています。ルート要素と名前空間に問題があります。JDOMの名前空間(デフォルト)

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=""> 
を、私はこのコードを使用

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

:私はこのルート要素を生成する必要があります

助けが必要ですか?あなたの時間をありがとう。

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