Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8547927
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T13:22:32+00:00 2026-06-11T13:22:32+00:00

I would like to know how to manipulate XML files in Java. I know

  • 0

I would like to know how to manipulate XML files in Java.

I know how to do the create and read, I am just missing how to do the update and delete them. If anyone knows a website with tutorials, about it I would appreciate it. I also would like to know how to manipulate the records.

Here is what I have so far:

/*
 * Classe de Lista de Compras
 */
package xml01;

public class ListaCompras {
    public String descricao;
    public int quant;
    public double valor;
}

package xml01;

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class GravarLer {

    static void gravar(String xml) {
        try {
            FileWriter w = new FileWriter("teste.xml");
            w.write(xml);
            w.close();
        } catch (Exception e) {
            System.out.println("Erro ao gravar XML: " + e);
        }
    }

    static String ler() {
        try {
            Scanner in = new Scanner(new File("testeler.xml"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNext()) {
                sb.append(in.next());
            }
            in.close();
            return sb.toString();
        } catch (Exception e) {
            System.out.println("Erro ao ler XML: " + e);
        }
        return "";
    }
}


/*
 * XStream
 */
package xml01;

import com.thoughtworks.xstream.XStream;

public class Xml01 {

    public static void main(String[] args) {
        // Cria um vetor de registros ListaCompras
        ListaCompras lista[] = new ListaCompras[10];
        // Inicializa os registros com numeros aleatorios
        for (int i = 0; i < lista.length; i++) {
            lista[i] = new ListaCompras();
            lista[i].quant = i + 2000 * i;
            lista[i].valor = i + 0.5 * 11 * i;
        }

        lista[0].descricao = "Arroz";
        lista[1].descricao = "Feijao";
        lista[2].descricao = "Macarrao";
        lista[3].descricao = "Agua mineral";
        lista[4].descricao = "Leite";
        lista[5].descricao = "Pão de forma";
        lista[6].descricao = "Manteiga";
        lista[7].descricao = "Banana";
        lista[8].descricao = "Laranja";
        lista[9].descricao = "Maçã";


        // Inicializa o XStream
        XStream xstream = new XStream();
        // Converte o objeto ListaCompras para XML
        String xml = xstream.toXML(lista);
        // Imprime na tela
        System.out.println(xml);

        // Chamando a classe GravarLer
        GravarLer ClasseGravar = new GravarLer();
        // Chamando o metodo
        GravarLer.gravar(xml);
        // GravarLer.ler();
        // System.out.println(GravarLer.ler());
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T13:22:33+00:00Added an answer on June 11, 2026 at 1:22 pm

    I just pull most of this from my personal code library. It lacks xPath, but the basic idea is there

    public final class TestXMLCRUD {
    
        public static void main(String[] args) {
            new TestXMLCRUD();
        }
    
        public TestXMLCRUD() {
    
            try {
    
                Document doc = createNewDocument();
                setRootNode(doc, "ThisIsTheRootNode");
    
                Element child = addElement(doc, "ThisIsAChildNodeOfRoot");
                addElement(doc, child, "ThisIsAChildNode", "I Have text!");
                System.out.println(save(doc));
    
            } catch (TransformerConfigurationException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (TransformerException ex) {
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            } catch (DOMException ex) {
                ex.printStackTrace();
            }
    
        }
        private DocumentBuilder builder;
    
        public Node getRootNode(Document xmlDoc) {
    
            Node nRoot = null;
    
            if (xmlDoc != null) {
    
                nRoot = xmlDoc.getDocumentElement();
    
            }
    
            return nRoot;
    
        }
    
        public Document createNewDocument() throws ParserConfigurationException {
    
            Document doc = getDocumentBuilder().newDocument();
            Element root = doc.createElement("root");
            doc.adoptNode(root);
            doc.appendChild(root);
    
            return doc;
    
        }
    
        public Element setRootNode(Document xmlDoc, String name) {
    
            removeNode(getRootNode(xmlDoc));
            Element root = xmlDoc.createElement(name);
            xmlDoc.adoptNode(root);
            xmlDoc.appendChild(root);
    
            return root;
    
    
        }
    
        public Document loadDocument(InputStream is) throws ParserConfigurationException, SAXException, IOException {
    
            return getDocumentBuilder().parse(is);
    
        }
    
        public Document loadDocument(File file) throws ParserConfigurationException, SAXException, IOException {
    
            return getDocumentBuilder().parse(file);
    
        }
    
        public Document loadDocumentFromString(String xml) throws ParserConfigurationException, SAXException, IOException {
    
            Document doc = null;
    
            ByteArrayInputStream bais = null;
    
            //StringReader sr = null;
            //InputSource is = null;
            try {
    
                bais = new ByteArrayInputStream(xml.getBytes());
    
                doc = loadDocument(bais);
    
            } finally {
    
    //            try { sr.close(); } catch (Exception e) { }
                try {
                    bais.close();
                } catch (Exception e) {
                }
    
            }
    
            return doc;
    
        }
    
        protected DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    
            if (builder == null) {
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(false); // You might want to change this...
                builder = factory.newDocumentBuilder();
    
            }
    
            return builder;
    
        }
    
        public Element addElement(Document xmlDoc, String name) {
    
            Element child = xmlDoc.createElement(name);
            getRootNode(xmlDoc).appendChild(child);
    
            return child;
    
        }
    
        public Node addElement(Document xmlDoc, Node node, String name) {
    
            Node child = xmlDoc.createElement(name);
            node.appendChild(child);
    
            return child;
    
        }
    
        public Node addElement(Document xmlDoc, Node node, String name, String text) {
    
            Node child = addElement(xmlDoc, node, name);
            child.setTextContent(text);
    
            return child;
    
        }
    
        public void removeNode(Node parentNode) {
    
            if (parentNode != null) {
    
                while (parentNode.hasChildNodes()) {
    
                    removeNode(parentNode.getFirstChild());
    
                }
    
                Node parent = parentNode.getParentNode();
                if (parent != null) {
    
                    parent.removeChild(parentNode);
    
                    NodeList childNodes = parent.getChildNodes();
                    if (childNodes.getLength() > 0) {
    
                        List<Node> lstTextNodes = new ArrayList<Node>(childNodes.getLength());
                        for (int index = 0; index < childNodes.getLength(); index++) {
    
                            Node childNode = childNodes.item(index);
                            if (childNode.getNodeType() == Node.TEXT_NODE) {
    
                                lstTextNodes.add(childNode);
    
                            }
    
                        }
    
                        for (Node node : lstTextNodes) {
    
                            removeNode(node);
    
                        }
    
                    }
    
                }
    
            }
    
        }
    
        public void save(Document xmlDoc, File fFile) throws TransformerConfigurationException, TransformerException, IOException {
    
            FileOutputStream fos = null;
    
            try {
    
                fos = new FileOutputStream(fFile);
                save(xmlDoc, fos);
    
                fos.flush();
    
            } finally {
    
                try {
                    fos.close();
                } catch (Exception e) {
                }
    
            }
    
        }
    
        public void save(Document xmlDoc, OutputStream os) throws TransformerConfigurationException, TransformerException, IOException {
    
            OutputStreamWriter osw = null;
    
            try {
    
                osw = new OutputStreamWriter(os);
                save(xmlDoc, osw);
                osw.flush();
    
            } finally {
    
                try {
                    osw.close();
                } catch (Exception exp) {
                }
    
            }
    
        }
    
        public String save(Document xmlDoc) throws TransformerConfigurationException, IOException, TransformerException {
    
            String sValue = null;
    
            ByteArrayOutputStream baos = null;
    
            try {
    
                baos = new ByteArrayOutputStream();
                save(xmlDoc, baos);
                baos.flush();
                sValue = new String(baos.toByteArray());
    
            } finally {
    
                try {
                    baos.close();
                } catch (Exception exp) {
                }
    
            }
    
            return sValue;
    
        }
    
        public void save(Document xmlDoc, Writer os) throws TransformerConfigurationException, TransformerException {
    
            Transformer tf = TransformerFactory.newInstance().newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty(OutputKeys.METHOD, "xml");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
            DOMSource domSource = new DOMSource(xmlDoc);
            StreamResult sr = new StreamResult(os);
            tf.transform(domSource, sr);
    
        }
    }
    

    Which generates…

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <ThisIsTheRootNode>
        <ThisIsAChildNodeOfRoot>
            <ThisIsAChildNode>I Have text!</ThisIsAChildNode>
        </ThisIsAChildNodeOfRoot>
    </ThisIsTheRootNode>
    

    Once you’ve digested all that, I’d have a read through

    • The Java xPath API
    • How to read XML using XPath in Java
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to read/write encrypted XML files using LINQ to XML. Does anyone
I know that I can use DOMDocument and DOMXPath to manipulate XML files. But,
I would like to know how we can create different user Roles for different
I would like to know if a class exists to manipulate date with symfony
I would like to know how to manipulate bits from a ByteArray. What I
i would like know some reference. I know i can googling it. but prefer
Would like to know what a programmer should know to become a good at
Would like to know the c# code to actually retrieve the IP type: Static
Would like to know how to integarate cruise control with maven? Cruise Control comes
Would like to know how to hide an div after a set of css3

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.