I am loading a xml and updating some value and then again saving the back. In this scenario the namespace prefix of the root element and all nodes is getting omitted.
I am working with Java version: JDK-17
There is no error in generating the output.
Input xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo:Config xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:foo="http://cc.bb.aa/def"> <foo:isEnabled >false</foo:isEnabled> </foo:Config>
output
<?xml version="1.0" encoding="UTF-8"?>
<Config xmlns:foo="http://cc.bb.aa/def" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<isEnabled>true</isEnabled>
</Config>
supporting code
public class UpdateElem {
public static void saveDocToFile(final Document doc, final Path file) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader((
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n"
+ " <xsl:output method=\"xml\" indent=\"yes\" encoding=\"UTF-8\"/>\n"
+ " <xsl:strip-space elements=\"*\"/>\n"
+ "\n"
+ " <xsl:template match=\"@*|node()\">\n"
+ " <xsl:copy>\n"
+ " <xsl:apply-templates select=\"@*|node()\"/>\n"
+ " </xsl:copy>\n"
+ " </xsl:template>\n"
+ "\n"
+ "</xsl:stylesheet>"
))));
// handle DOCTYPE setting
if (doc.getDoctype() != null) {
String systemValue = doc.getDoctype().getSystemId();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue);
}
transformer.transform(new DOMSource(doc), new StreamResult(file.toFile()));
} catch (TransformerFactoryConfigurationError | TransformerException e) {
e.printStackTrace();
}
}
public static Document getDocument(final Path file) {
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
Document doc = null;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(file.toFile());
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
public static void main(String[] args) {
Path xml = Paths.get("user.xml").normalize();
Document doc = getDocument(xml);
NodeList sslConfig = doc.getElementsByTagName("foo:Config");
System.out.println("sslConfig= "+sslConfig);
Element sslConfigElement = (Element) sslConfig.item(0);
NodeList nodeList = sslConfigElement.getElementsByTagName("foo:isEnabled");
if ("true" != null && !nodeList.item(0).getTextContent().equals("true")) {
nodeList.item(0).setTextContent("true");
}
try {
saveDocToFile(doc, xml);
} catch (Exception e) {
e.printStackTrace();
}
}```