How to search and replace in an xml file using java

Hi all,
I am new to java and Xml Programming.
I have to search and replace a value Suresh with some other name in the below xml file.
Any help of code in java it is of great help,and its very urgent.
I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
Thanks in advance.
**XML File*
<?xml version="1.0" encoding="ISO-8859-1"?>
<student>
<stud_name>Suresh</stud_name>
<stud_age>40</stud_age>
</student>Also i am using SAX Parser in the java program
any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
Edited by: Karthik84 on Aug 19, 2008 1:45 AM
Edited by: Karthik84 on Aug 19, 2008 3:15 AM

Using XPath to locate the elements you are after is very easy.
Try something like this:
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class BasicXMLReplaceWithDOM4J {
     static String inputFile = "C:/student.xml";
     static String outputFile = "C:/studentRenamed.xml";
     public static void main(String[] args) throws Exception {
          // Read xml and build a DOM document
          Document doc = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder().parse(new InputSource(inputFile));
          // Use XPath to find all nodes where student is named 'Suresh'
          XPath xpath = XPathFactory.newInstance().newXPath();
          NodeList nodes = (NodeList)xpath
               .evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
          // Rename these nodes
          for (int idx = 0; idx < nodes.getLength(); idx++) {
               nodes.item(idx).setTextContent("Suresh-Renamed");
          // Write the DOM document to the file
          Transformer xformer = TransformerFactory.newInstance().newTransformer();
          xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
}- Roy

Similar Messages

  • What is the best cheap/free search and replace software for .xml files?

    Transferring my iTunes library from PC to Mac I have reached the stage where I want to edit the .xml file from PC file paths to Mac ones - which would be the best preferrably free software to do this on?

    Perhaps my comment in your other thread will help.
    tt2
    PS I don't know about the Mac, but Notepad++ will probably do your search & replace on the PC if you have to edit the XML.
    Message was edited by: turingtest2

  • How to delete a perticular node from xml file using java code

    Hii All,
    Now i am trying to delete a perticular node from xml file.Like...
    XML file:
    <Licence>
    <SERVER>
    <was id="1">1</was>
    <was id="2">2</was>
    </SERVER>
    </LICENCE>
    I am working in messaging service using JABBER framework with whiteboard facility.
    Here Some commands i have created to add,modify,delete nodes from xml file.They Are
    1.If u want to add a new node then.
    create Licence.SERVER <ss id="3">ddd</ss> lic.xml
    (here u want to add a new node called "ss" under Licence.SERVER.
    And lic.xml is tyhe xml file name where it was saved.
    2.If u want to delete a node(Suppose <was id="1">),then the command should be
    delete Licence.SERVER.was:id='"1" lic.xml
    A problem arises that here it find two was attributes.And it delete the last was attribute,not the requested node.
    PLEASE HELP ME IN SOLVING THIS CODE..
    ------------------------------------

    Looks like you clicked on "Post" before you pasted in the code you were talking about.

  • How to read and parse a remote XML file with Java

    Hi.
    Using J2SE v1.4.2, I'd like to read and parse a remote file:
    http://foo.com/file.xml
    Is it possible with Java? I'd be extremely grateful if someone could provide me any webpage showing a very simple code.
    Thank you very much.

    How about the following?
         import java.io.InputStream;
         import java.net.URL;
         import javax.xml.parsers.DocumentBuilder;
         import javax.xml.parsers.DocumentBuilderFactory;
         import org.w3c.dom.Document;
         public static void main(String[] args) throws Exception {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              URL url = new URL("http://foo.com/file.xml");
              InputStream inputStream = url.openStream();
              Document document = db.parse(inputStream);
              inputStream.close();
         }-Blaise

  • In Pages, how to search and replace text involving invisible characters?

    In Pages documents, how to search and replace text involving invisible characters, colors and font sizes—a task which is so easy in Mircosoft Word?

    I read that an older version of Pages allowed users to enter special characters in the search/replace fields, but this did not work for me.
    Here: http://www.macworld.com/article/1156533/pagesspecialcharacters.html
    I still am looking for a way to do this.

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • How to read the data from Excel file and Store in XML file using java

    Hi All,
    I got a problem with Excel file.
    My problem is how to read the data from Excel file and Store in XML file using java excel api.
    For getting the data from Excel file what are all the steps i need to follow to get the correct result.
    Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
    Thanks & Regards,
    Sreenu,
    [email protected],
    india,

    If you want someone to do your work, please have the courtesy to provide payment.
    http://www.rentacoder.com

  • How to write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • Merging 2 message history xml files using java

    hi., i'm new to xml programming..
    well..., i got homework bout it..., and got a lot of problems to write it..
    could you help me a favor??
    I need to write a homework bout merging 2 MSN mssg history files (xml files) using java.
    At least need to maintain their date, time, sender, receiver, and information(sayings)....and are ordered using time..
    can u help me??

    Well, show us what you've got and where you are having difficulty.

  • How to parse and retrieve records from xml files into columns in Table

    Hi
    I attached the thing what i tried.
    Table to hold the XML COntent:
    create table xmlfile(xml_con sys.xmltype);
    Inserting Xml file content into the Above table:
    insert into xmlfile values(sys.xmltype.CreateXml('<Root><name>RAM</name><age>23</age></Root>'))
    SQL> select * from xmlfile;
    XML_CON
    <Root>
    <name>RAM</name>
    <age>23</age>
    </Root>
    SQL> select extractValue(xml_con, '/Root/name') content from xmlfile;
    CONTENT
    RAM
    This one works fine
    But if the file content is as below( contains MUltiple Records)
    insert into xmlfile values(sys.xmltype.CreateXml('<Root><Record><name>RAM</name><age>23</age></Record><Record><name>SAM</name><age>23</age></Record></Root>'))
    SQL> select extractValue(xml_con, '/Root/Record/name') content from xmlfile;
    ERROR at line 1:
    ORA-19025: EXTRACTVALUE returns value of only one node
    Can anyone help me 4 this issue-How to extract multiple records from the XML file inthis manner(from PL/SQL without using JAVA)
    OR
    If there is anyother way to do this please tell me?

    SQL> SELECT EXTRACTVALUE (COLUMN_VALUE, '//name') NAME,
           EXTRACTVALUE (COLUMN_VALUE, '//age') age
      FROM TABLE
              (XMLSEQUENCE
                  (EXTRACT
                      (XMLTYPE
                          ('<Root>
                              <Record>
                                <name>RAM</name>
                                <age>23</age>
                              </Record>
                              <Record>
                                <name>SAM</name>
                                <age>23</age>
                              </Record>
                            </Root>'
                       '/Root/Record'
    NAME       AGE      
    RAM        23       
    SAM        23       
    2 rows selected.

  • How to read the attribute of the xml file using jaxb

    Thanks,
    Buddy as i have a issue i have to read the xml file using jaxb and xml file contains this data and i have read the attribute like name , desc and action for a particular menu name pls tell the code how to do this it will be a great favour to me
    thanx in advance
    Rasool
    <contextmenu>
    <menu name='Lead' >
    <menuitem name='newlead' desc='New Lead' action='/leads.do?dispatch=insert' />
    <menuitem name='editlead' desc='Edit Lead' action='' />
    <menuitem name='leadinfo' desc='Lead Information' action='' />
    </menu>
    <menu name='Cases' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    <menu name='Contact' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    </contextmenu>

    What my program do is to get the encoding of XML files and convert them to UTF-8 encoding files, while I need this "encoding" information of the original XML document thus I can convert...
    After reading specifications and JDOM docs, the truth turns to be disappointed, no function is provided to get this information in JDOM level 2(the current released one), while it's promissed that this function will be provided in JDOM level API....
    Thanx all for your help and attention!!!

  • How Do I write an XML file using Java?

    Hello there!! to everyone reading my post.
    I have this project I need to do, and I have no clue where to start, I was wondering if you guys could help me out.
    I need to know how to write an XML file using a Java Program, but without using a Third party library.... just using java native APIs.
    I will probably take the values to construct the file from a form.
    I will certainly appreciate if you could post some sample code for me.
    Thank you very much in advance..

    Hello there!,
    I have some doubts about the Tutorial I am currently reading. correct me If I'm wrong, but the section "Write a simple XML file" teaches you how to do so using a text editor. I need to create my XML file from a running Java Program written by myself, that takes the values to build it from some variables.
    If I'm totally wrong about what I'm saying, could you please point me to where I can find the information of how to do what I'm asking for, inside the tutorial.
    Thank you very much,...
    sincerely.

  • Java and XML :: Unlocking, editing and locking an XML file using JAVA

    I need to develop a form with Address field , When i enter address information and submit the form it needs to generate an
    XML file for furthur processing.
    Now my problem is :
    When i want to edit the address....after submitting the form by entering the address information, it should unlock
    the XML and edit the XML and then lock it.
    How can i achive programatically, unlocking an XML file, editing the file, and locking it?.
    Thanks,
    Maruthi.

    There's a FileLock class, you know, in the java.nio.channels package. However before you start using it you should read its API documentation carefully including statements like " Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified".
    Personally I would say that if you need to synchronize access to this XML file, you should consider changing your design to use something that supports locking a bit better, like a database. Or by writing a server that encapsulates the XML file and accepts requests to read it and update it, serializing those requests appropriately.

  • How to validate and transform large (180M) xml files

    Hi:
    I've been looking at various ways to do this with oracle and am getting a bit lost in the sea of documentation and different ways to go about this. I was hoping that something like the XMLParser class and XMLTransform would be smart enough to handle large files by using SAX when it has to but I'm getting "too many nodes" when trying to transform a really large file. I've gotten oraxsl to handle it if I pass in the proper memory parameters on the command line but a) this will still have limits and b) I was trying to do this in a stored procedure which (I think) means I'm looking at XMLParser?
    I've also seen documentation on something called "Scalable DOM" but I think that's only in 11g? So I'm thinking I have to write a (Java?) stored procedure to loop through the top elements of this XML file (select extract(...)) and transform each node?
    I have the XML, XSD, and XSLT all in clob columns. What's the easiest/quickest path within Oracle to validate the XML against the xsd and translate source XML with XSL?
    I'm using Oracle 10gR2 on RH Linux.
    Thanks.

    So I'm thinking I have to write a (Java?) stored procedure to loop through the top elements of this XML file (select extract(...)) and transform each node? Here's something I've written a while back when I hit the same restrictions ("too many nodes") on 10.2.0.4.
    It takes XMLType as input parameters (but it's easy to adapt for CLOB), and streams the transformed XML directly into a file :
    create or replace and compile java source named ora_xslt_util as
    import oracle.xml.parser.v2.*;
    import oracle.xdb.XMLType;
    import java.io.*;
    import org.w3c.dom.*;
    public class oraXSL
    private static XMLDocument getXMLDocument(XMLType xml) throws Exception
        XMLDocument doc = null;
        DOMParser parser  = new DOMParser();
        parser.setValidationMode(oracle.xml.parser.v2.XMLParser.NONVALIDATING);
        parser.setPreserveWhitespace(true);
        parser.parse(new StringReader(xml.getStringVal()));
        doc = parser.getDocument();
        return doc;
    public static void transform(XMLType doc, XMLType xsl, String filename) throws Exception
        OutputStream os = new FileOutputStream(filename);
        XMLDocument xmldoc = getXMLDocument(doc);
        XMLDocument xsldoc = getXMLDocument(xsl);
        XSLProcessor xsp = new XSLProcessor();
        XSLStylesheet xss = xsp.newXSLStylesheet(xsldoc);
        xsp.processXSL(xss, xmldoc, os);
        os.close();
    }and the PL/SQL wrapper (originally part of a package) :
    PROCEDURE processXSL (
       p_xmldoc IN XMLType
    , p_xsldoc IN XMLType
    , p_filename IN VARCHAR2
    IS
    LANGUAGE JAVA NAME 'oraXSL.transform(oracle.xdb.XMLType,oracle.xdb.XMLType,java.lang.String)'
    ;

Maybe you are looking for