views:

29

answers:

1

I am using XOM to build XML documents in Java.

I have created a simple XML document, and I want an XML namespace. But when I set the namespace on the first tag, an empty namespace is set on the childs like xmlns="", how can I get rid of this behaviour? I only want xmlns on the first tag.

I want this XML:

<request xmlns="http://my-namespace"&gt;
    <type>Test</type>
    <data>
        <myData>test data</myData>
    </data>
</request>

But this is the XML document output from XOM

<request xmlns="http://my-namespace"&gt;
    <type xmlns="">Test</type>
    <data xmlns="">
        <myData>test data</myData>
    </data>
</request>

This is my Java XOM code:

String namespace = "http://my-namespace";
Element request = new Element("request", namespace);

Element type = new Element("type");
type.appendChild("Test");

request.appendChild(type);

Element data = new Element("data");
request.appendChild(data);

Element myData = new Element("myData");
myData.appendChild("test data");
data.appendChild(myData);

Document doc = new Document(request);
doc.toXML();
+1  A: 

This works for me. However, I'm a bit puzzled as to why the Element objects don't inherit the namespace of their parents, though. (Not an XML nor XOM expert)

Code:

String namespace = "http://my-namespace";
Element request = new Element("request", namespace);

Element type = new Element("type", namespace);
type.appendChild("Test");

request.appendChild(type);

Element data = new Element("data", namespace);
request.appendChild(data);

Element myData = new Element("myData", namespace);
myData.appendChild("test data");
data.appendChild(myData);

Document doc = new Document(request);
System.out.println(doc.toXML());

Output:

<?xml version="1.0"?>
<request xmlns="http://my-namespace"&gt;
  <type>Test</type>
  <data>
    <myData>test data</myData>
  </data>
</request>
Catchwa
From the javadoc Element(String) "Creates a new element in no namespace"
Michael Rutherfurd