fusi0n
fusi0n

Reputation: 1079

Java XML modifying

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?

Upvotes: 1

Views: 288

Answers (1)

Anthony Accioly
Anthony Accioly

Reputation: 22481

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:

Upvotes: 2

Related Questions