gcotis
gcotis

Reputation: 117

XML Namespace - xmlns

I'm trying to generate a XML from Java.

Something like this:

<?xml version="1.0" encoding="UTF-8"?>

<ElementFile 
  xmlns="http://www.url.com/bla/bla" 
  xmlns:common="http://www.url.com/bla/bla/bla">
  <Regulation>
    <blablaElement>0000-0000</blablaElement>
  </Regulation>
</ElementFile>

To do this, I wrote the following code:

ElementFile = document.addElement( "ElementFile" )
  .addNamespace("xmlns","http://www.url.com/bla/bla") 
  .addNamespace("common", "http://www.url.com/bla/bla/bla");

But the generated code is:

<?xml version="1.0" encoding="UTF-8"?>

<ElementFile 
  xmlns:xmlns="http://www.url.com/bla/bla" 
  xmlns:common="http://www.url.com/bla/bla/bla">
  <Regulation>
    <blablaElement>0000-0000</blablaElement>
  </Regulation>
</ElementFile>

However, if I write this (without xmlns)

ElementFile = document.addElement( "ElementFile" )
  .addNamespace("","http://www.url.com/bla/bla") 
  .addNamespace("common", "http://www.url.com/bla/bla/bla");

Then, the xml generates the line properly but it adds xmlns=" " by default:

<?xml version="1.0" encoding="UTF-8"?>

<ElementFile 
  xmlns="http://www.url.com/bla/bla" 
  xmlns:common="http://www.url.com/bla/bla/bla">
  <Regulation xmlns="">
    <blablaElement>0000-0000</blablaElement>
  </Regulation>
</ElementFile>

I'm quite lost...

[UPDATED QUESTION]

I'm sorry, but I don't understand how to integrated your answer in my code. I am new to this domain.

My complete code is:

XMLWriter writer = new XMLWriter(new FileWriter("xmlFileName"), format);

Document document = DocumentHelper.createDocument();

Element ElementFile = document.addElement( "ElementFile" )
    .addNamespace("xmlns","http://www.url.com/bla/bla") 
    .addNamespace("xmlns:common", "http://www.url.com/bla/bla/bla");

Element Regulation = ElementFile.addElement( "Regulation" );
    Element blablaElement = Regulation.addElement( "blablaElement" )
        .addText( "0000-0000" );                

writer.write(document);
writer.close();

Upvotes: 0

Views: 2157

Answers (1)

X-Pippes
X-Pippes

Reputation: 1170

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
DOMImplementation domImpl = docBuilder.getDOMImplementation();    
Document doc = domImpl.createDocument("http://www.url.com/bla/bla", "ElementFile ", null);
doc.setXmlVersion("1.0");
doc.setXmlStandalone(true);

Element elementFile = doc.getDocumentElement();
elementFile.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:common","http://www.url.com/bla/bla/bla");

and add elements to this doc

you have a similar question here: How to create attribute (xmlns:xsd) to XML node in Java?

Upvotes: 1

Related Questions