Link to home
Create AccountLog in
Java

Java

--

Questions

--

Followers

Top Experts

Avatar of anup001
anup001

update xml document using java
how do I update an xml file using java. I just want to update a tag value that is already existing. For example the tag is

<name>xyz</test>

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of kawaskawas🇺🇸

that isnt valid xml ... also, most parsers wont allow you to change the tag name. you could consider using xsl to transform a document into a what you need.

the following has an example of how to get things done with xsl. http://www.exampledepot.com/egs/javax.xml.transform/BasicXsl.html

Avatar of kawaskawas🇺🇸

having re-read this, it may be that you only want to update the text content, i.e. 'xyz' in your example? if that is the case, that is fairly straightforward. example in this case is derived from http://javaalmanac.com/

    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
   
    public class BasicDom {
        public static void main(String[] args) {
            Document doc = parseXmlFile("infilename.xml", false);
            // Obtain a node
            Element element = (Element)doc.getElementsByTagName("name").item(0);
            // set the textContent
            element.setTextContent("my new text");
            // write to a file
            // refer to http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/xslt/2_write.html
        }
   
        // Parses an XML file and returns a DOM document.
        // If validating is true, the contents is validated against the DTD
        // specified in the file.
        public static Document parseXmlFile(String filename, boolean validating) {
            try {
                // Create a builder factory
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(validating);
   
                // Create the builder and parse the file
                Document doc = factory.newDocumentBuilder().parse(new File(filename));
                return doc;
            } catch (SAXException e) {
                // A parsing error occurred; the xml input is not valid
            } catch (ParserConfigurationException e) {
            } catch (IOException e) {
            }
            return null;
        }
    }


Avatar of anup001anup001

ASKER

yes sorry i mistyped it, i just want to update the value i.e xyz.

the ccorrect xml is

<name>xyz</name>

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of anup001anup001

ASKER

element.setTextContent("my new text"); does not seem to be working. It does not do anything.

Avatar of kawaskawas🇺🇸

replace
     element.setTextContent("my new text");

with the following:

Node parent = element.getParentNode();
parent.removeChild(element);
element.setTextContent("my new text");
parent.appendChild(element);

Avatar of anup001anup001

ASKER

i get this error

GetRootNode.java:43: cannot resolve symbol
symbol  : method setTextContent (java.lang.String)
location: interface org.w3c.dom.Element
element.setTextContent("my new text");

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of kawaskawas🇺🇸

can you post all of your code?

Avatar of anup001anup001

ASKER


import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.net.URL;

import java.lang.Object;
import java.io.IOException;
import java.io.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class GetRootNode{
  public static void main(String[] args) {
    try{
     BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

      File file = new File("filename.xml");
      if (file.exists()){
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fact.newDocumentBuilder();
        Document doc = builder.parse("filename.xml");
        Node node = doc.getDocumentElement();
        String root = node.getNodeName();
        System.out.println("Root Node: " + root);            
      Element element = (Element)doc.getElementsByTagName("NAME").item(0);
      
Node parent = element.getParentNode();
parent.removeChild(element);
element.setTextContent("my new text");
parent.appendChild(element);

      System.out.println("Node Name"+ element.getNodeName());
            
      TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();
   
    Source src = new DOMSource(doc);
   
    javax.xml.transform.Result dest = new StreamResult(file);
    aTransformer.transform(src, dest);
              System.out.println("Changed Element: " + element);
                    System.out.println("ya "+element.getChildNodes().getLength());
                    System.out.println("no "+element.getChildNodes());
                              
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch(Exception e){}
  }
}

Avatar of kawaskawas🇺🇸

you are probably using java 1.4 ... try element.setNodeValue("my new text"); instead of element.setTextContent("my new text");

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of anup001anup001

ASKER

And this <NAME> tag is in the root node. If i ahev to update a tag value that is within a tag, how do i do it?

<ADDRESS>
         <CITY>
                      abc city
         </CITY>
</ADDRESS>

Avatar of kawaskawas🇺🇸

assuming that their is only one node with that name, do
    getElementsByTagName("NAME").item(0);
if there are more, you will have to iterate over them
read http://java.sun.com/j2se/1.4.2/docs/api/org/w3c/dom/Element.html, specifically getElementsByTagName()

Avatar of anup001anup001

ASKER

ok wil try that for node within node however

element.setNodeValue("my new text");  does not work. I tried that yesterday also. is there any other work around?

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of kawaskawas🇺🇸

an alternative would be to try the method createTextNode() [http://www.exampledepot.com/egs/org.w3c.dom/AddText.html, http://java.sun.com/j2se/1.4.2/docs/api/org/w3c/dom/Document.html].

Also, if its possible, can you upgrade to java 1.5?

Avatar of anup001anup001

ASKER

so if i try to use this it works but it does not replace the old value. It only appends to the existing value. Can we replace the old value using this?


 Text text = doc.createTextNode("test123");
  text.setData("hello");
  element.appendChild(text);

Avatar of kawaskawas🇺🇸

Element element = (Element)doc.getElementsByTagName("NAME").item(0);
Node parent = element.getParentNode();
parent.removeChild(element);
Text text = doc.createTextNode("test123");
text.setData("hello");
parent.appendChild(text);

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of anup001anup001

ASKER

it is removing the tag but not putting it back again.

Avatar of kawaskawas🇺🇸

is this what you want?

Element element = (Element)doc.getElementsByTagName("NAME").item(0);
Node parent = element.getParentNode();
parent.removeChild(element);
Text text = doc.createTextNode(element.getTagName()); // set name to be old name ...
text.setData("hello");
parent.appendChild(text);

Avatar of kawaskawas🇺🇸

the only problem with that is now if the node that you are setting the text to contains other nodes, they will disappear ... if you insist on using java 1.4, you should download  Xerces-J and place the libraries in your <java-home>\lib\endorsed directory...

Then use the original method that i stated above, namely setTextContent ...

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of anup001anup001

ASKER

cool let me try that thanks a lot for all the info.

Avatar of anup001anup001

ASKER

so is there somethign i need to importafter puting these xerces libraries in the java home?

ASKER CERTIFIED SOLUTION
Avatar of kawaskawas🇺🇸

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account
Java

Java

--

Questions

--

Followers

Top Experts

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.