1
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class modifyXML {

    public static void modify(StringBuffer XMLBuffer) throws IOException, ParserConfigurationException, SAXException{

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();   
        Document doc = db.parse(new ByteArrayInputStream(XMLBuffer.toString().getBytes()));
        Element rootNode = doc.getDocumentElement();

        NodeList priceList = rootNode.getElementsByTagName("price");
        priceList.item(0).setTextContent("190");

        NodeList inStockList = rootNode.getElementsByTagName("id_product_attribute");
        inStockList.item(0).setTextContent("100");



    }
}

I am trying to modify an XML file and then put it all back together. I have managed with the modifying part, but I can not get the XML file back together. The result can be either a String or a StringBuffer.

What is the best/easiest way to do this?

fusi0n
  • 1,059
  • 3
  • 12
  • 21
  • Whats the relevance of your code? Your question doesn't refer to it at all... – Robert H Jul 04 '13 at 12:29
  • Lateral suggestion: use a less idiotic XML API that doesn't bury this functionality, like JDOM. (No, I'm not a fan of the standard DOM.) – millimoose Jul 04 '13 at 13:22

1 Answers1

2

Use a Transformer as described by WhiteFang34 in XML Document to String.

Official Java Tutorials: Writing Out a DOM as an XML File (just make StreamResult Wrap something else such as StringWriter).

Update:

Less known, shorter alternative by ykaganovich based on Load / Save objects:

Community
  • 1
  • 1
Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
  • 2
    For pretty printed XML (indentation) look [here](http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java). Look not at the chosen answer but with `TransformerFactory`. – Joop Eggen Jul 04 '13 at 12:27
  • Post by WhiteFang was pretty clear and straight-forward, I recommend that. Thank you for your answer. – fusi0n Jul 04 '13 at 17:05