0

I have the following codeblock at the beginning of building an XML in Java. ROOT_ELEM is obviously the root element.

 try{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.newDocument();

        root = doc.createElementNS(NS,"xsi:" + ROOT_ELEM);
        doc.appendChild(root);
    } catch (ParserConfigurationException e) {
        LOG.error("Unable to create an XML document.", e);
    }

The root = doc.createElementNS(NS,"xsi:" + ROOT_ELEM); part adds the namespace with the xsi prefix for the XML line:

<xsi:rootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

My problem is that I need the xsi on the xmlns:xsi=... part but not on the xsi:rootElement part. Is this possible? I know I can convert the whole thing to a String and do a search and replace but that's hackish and I wanted to know if there is a way to do with methodically with the DOM Parser api. Here is the line I want:

<rootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
user3813942
  • 311
  • 1
  • 3
  • 13
  • Without the `xmlns:xsi` attribute, `xsi` is not a valid prefix, which would make your XML invalid. You can, however, define `xmlns:xsi` on any ancestor element instead of defining it on `rootElement`. – VGR Oct 13 '16 at 13:14
  • Right, I want to keep the xmlns:xsi part but the prefix before rootElement, xsi:rootElement, is the part I want to erase. When I do it manually the XML is valid. – user3813942 Oct 13 '16 at 13:26
  • Then why pass `"xsi:" + ROOT_ELEM`? – VGR Oct 13 '16 at 14:32
  • Because that adds the namespace property to that element. Do you know of a different method I should be using? – user3813942 Oct 13 '16 at 14:37
  • 1
    See http://stackoverflow.com/a/13048523/1831987 . – VGR Oct 13 '16 at 14:43

0 Answers0