1

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();
        }

    }```

1 Answer 1

1

Try setting the DocumentBuilderFactory to be namespace-aware.

docBuilderFactory.setNamespaceAware(true)

(Also, there's no point building a DOM just for the sake of transforming it. Most XSLT processors will build a more efficient tree if you give them a SAXSource or StreamSource.)

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Michael, this solution works but when i try to find an element it fails. final XPath xpath = XPathFactory.newInstance().newXPath(); Node result = (Node) xpath.compile("/foo:Config/foo:isEnabled").evaluate(doc, XPathConstants.NODE); System.out.println(result); This returns null
If you use namespace prefixes in an XPath expression then you need to declare them, using xpath.setNamespaceContext().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.