How to change the value of an element in xml in java?

Tags: ,



I have the following code that parses an xml and get the value of an element:

        NodeList elem = dom.getElementsByTagName("quantity");
        LOG.info("elem.getLength: " + elem.getLength());
        int quantity = -1;
        for (int i = 0; i < elem.getLength(); i++) {
            Element linenl_quantity = (Element) elem.item(i);
            LOG.info(linenl_quantity.getAttributes().getNamedItem("value").getNodeValue());
            quantity = toInteger(linenl_quantity.getAttributes().getNamedItem("value").getNodeValue());
            linenl_quantity.setAttribute("value", String.valueOf(quantity));
        }

When I call the line linenl_quantity.setAttribute("value", String.valueOf(quantity)) I get the following error:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: getWriter() has already been called for this response

I need to the the float value of the element <quantity value="1.0" /> and change it to <quantity value="1" />. I manage to get the value, but how can I change it?

Answer

I found the solution.

I edited the code as below and moved it to another class (file).

NodeList elem = dom.getElementsByTagName("quantity");
int quantity = -1;
for (int j = 0; j < elem.getLength(); j++) {
    Element linenl_quantity = (Element) elem.item(j);
    quantity = (int)Double.parseDouble(linenl_quantity.getAttributes().getNamedItem("value").getNodeValue());
    LOG.info(String.valueOf(quantity));
}


Source: stackoverflow