Home > Mobile >  Loading XML into DOmSource is adding xmlns="" to all bean tags
Loading XML into DOmSource is adding xmlns="" to all bean tags

Time:09-18

I am trying to programmatically edit an XML file by loading it into a Document object and manipulating it there. This portion on the program works however if I load the XML into either an InputStream or write it back to a file, all the bean tags have xmlns="" attribute added to them.

So if before I had:

<bean id="discoverySpi" class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
    <property name="ipFinder" ref="ipFinder" />
</bean>

I get back out:

<bean xmlns="" class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi" id="discoverySpi">
    <property name="ipFinder" ref="ipFinder"/>
</bean>

This happens to all bean tags weather or not they are edited. I verified that simply reading the XML file and writing it back out with the following code without making any changes to the Document object still causes the error.

I assume this is happening when I create the DOMSource object but do not know how to stop this from happening.

Currently these added attributes are causing errors when I try to use the XML file.

String XML_PATH = "./some/path/in/project/someXML.xml";

DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBF.newDocumentBuilder();
Document doc = docBuilder.parse(XML_PATH);

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File("./some/output/path/modifiedXml.xml"));
transformer.transform(domSource, streamResult);

CodePudding user response:

Firstly, add

docBF.setNamespaceAware(true);

Secondly, make sure that whenever you add an element programmatically to the DOM, you use the namespace-aware versions of the methods, for example createElementNS().

Consider using a library such as XOM or JDOM2 in preference to DOM. The popularity of DOM never ceases to astound me when far better alternatives are available.

  • Related