Search and Replace XML TAG using JAVA

Hi All,
I have an XML file, say RESULT.XML Which has about 30000 Lines (yes Thirty Thousand ). For some reason i need to replace an existing tag with a different tag(not the value inside the tag, But the tag itself) . I am facing a challenge. I will explain it as below.
I have a csv file which has 2 values as given below
<VALUE A> , <VALUE B>
where <VALUE A> is an existing node in the RESULT.XML and <VALUE B> is the node that should replace <VALUE A> in the RESULT.XML
i have 500 such entries in the file.
Now i need to write a program to read the csv file, Search <VALUE A> in the RESULT.XML and Replace it with <VALUE B> of the csv file.
please let me know how do i start with this.
I really want to fix this issue.
Existing Node = <Product ID="role (contact) 3" UserTypeID="Product Number">_
To be changed to = <Product ID= role (contact)3" UserTypeID="Product Number">_
please reply if you need any further information
Thanks in Advance
Manzoor

Sounds like a job for XSLT or Perl not Java though it can be done in Java. In Java I would initially try
1) Read the csv file using one of the many free CSV parsers and build a Map<String,String>.
2) Create a Rewriter using the map keys as targets and use the map values as replacements.
3) Read the XML file line by line and process each line with the Rewriter.
4) Save each line to an output file.
For a one-off task this would probably serve but it could prove very slow if you need to run this on a daily basis.

Similar Messages

  • Q: How to access and modify xml tags using Java

    I have an xml based document that i need to access and change. For example, the code
    <section id="section1">
    <div>
    <xforms:group id="id1">
    <xforms:label id="label1">
    <l style="font-size:16pt"> something </l>
    </xforms:label>
    </xforms:group>
    </div>
    </section>
    Working with Java I need to access all the tags, select some of them that are relevant to the current device and remade the document. I thought I would read the file character by character identifying the different labels and building a tree, storing in the tree nodes the relevant information as some kind of attributes (for example, in the case of the <xforms:group id="id1"> I would name the node "xforms:group" and create an "id" attribute with value "id1"). I'm not sure if that is the most efficient way of accessing the problem (computational power might be an issue), and would appreciate some help on the subject.
    Thanks,

    this may help you..
    this is a little util i made to help me read/write files.
    using this, you are only one step away from your solutions, you only need to figure out the regex you need to run on the text of the file to make it become what you need it to become.
    though if you use non-standard encoding, you might not want to use this code..
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    public class ASCIIFile {
         private File file;
         private StringBuilder builder;
         public ASCIIFile(String path) throws IOException{
              file = new File(path);
              openFile();
         public ASCIIFile(File file) throws IOException{
              this.file = file;
              openFile();
         public void setNewFileName(String fileName){
              file = new File(file.getAbsolutePath(), fileName);
         public void setNewFilePath(String filePath){
              file = new File(filePath, file.getName());
         private void openFile() throws IOException{
              if(!file.exists()) file.createNewFile();
              BufferedReader read = new BufferedReader(new FileReader(file));
              String line = read.readLine();
              builder = new StringBuilder();
              while(line != null){
                   builder.append(line);
                   builder.append("\n");
                   line = read.readLine();
              read.close();
         public String getContents(){
              return builder.toString();
         public StringBuilder getStringBuilder(){
              return builder;
         public void setStringBuilder(StringBuilder b) throws IOException{
              setContents(b.toString());
         public void setContents(String contents) throws IOException{
              FileWriter writer = new FileWriter(file);
              writer.write(contents);
              writer.flush();
              writer.close();
              builder = new StringBuilder(contents);
         public static File[] getAllFilesUnderDir(String fullpath, boolean recursive) {
              ArrayList queue = new ArrayList(10);
              ArrayList matched = new ArrayList();
              File root = new File(fullpath);
              File[] files = root.listFiles();
              if (files == null || files.length == 0) {
                   return new File[] {};
              queue.addAll(Arrays.asList(files));
              for (int j = 0; j < queue.size(); j++) {
                   File child = (File) queue.get(j);
                   if (child.isDirectory() && recursive) {
                        files = child.listFiles();
                        if (files != null) {
                             queue.addAll(Arrays.asList(files));
                   } else { // child is file
                        matched.add(child);
              return (matched.size() > 0)?((File[]) matched.toArray(new File[] {})):(new File[] {});
    }

  • How to create nested xml tags using java parser?

    Hi,
    I need to create a xml file containing following tags using java program-
    <A attr1="abc">
    <B attr2="xyz">
    <C attr3="pqr"> </C>
    </B>
    </A>
    Can anyone please let me know which parser should I use to create the above mentioned xml file?
    If possible, please post a code snippet for the same.
    Thanks in advance..

    Well, you could start by doing it all the 'old fashioned' way; create a String object containing that text and then write it away to a file. Or you could take the time to look at the javadoc for all of the xml support that the Java language itself supplies - XMLReader/Writer for a start. After that put together some code that you think would do the job and ask for help on any specific problems you encounter.

  • How can i find and replace xml tags?

    Hi, i am using xml in my workflow and want to be able to remove certain tags if they contain particular text.
    here is an example of my xml structure…
    <entry>
        <name>DEFAULT</name>
        <tel>DEFAULT</tel>
        <address>DEFAULT</address>
    </entry>
    I am using this initial structure to set the paragraph styles to be followed when the xml data is imported.
    This leaves DEFAULT in place wherever an entry doesn't have any content for that field.
    I want to be able to import my XML then run a script that removes any tags that include DEFAULT, - I need the entire xml tag to be removed not just the text, if i do a normal find and replace it will only remove the text not the tags which is causing problems with styling. I also want to remove the end of para/return (^p) that i've placed at the end of the line. So it would be the same as opening up story editor and removing the content + tags + hard return in there, but i want to automate the process…
    So i think this is what i need to search for in each case
    "<name>DEFAULT</name>^p"
    and i want to replace it with nothing ""
    Can this be done through scripting (ideally javascript)?
    I have a little knowledge of javascript but am not sure how to search and target that kind of string in indesign...
    using indesign cs5
    many thanks

    Hi,
    Script should do it in two steps:
    1. find all occurences of i.e. ">DEFAULT<"
    2. remove whole paragraph which is a found_text's container.
    For example this way -JS - (a textFrame filled with your text should be selected) :
    var mStory = app.selection[0].parentStory;
    app.findTextPreferences =  null;
    app.findTextPreferences.findWhat = ">DEFAULT<";
    var myF = mStory.findText();
    var count = myF.length;
    while (count--)
         myF[count].paragraphs[0].remove();
    rgds

  • How to replace XML elements using java

    I have been usint SAX 2.0 and DOM Level 2 api's to represent XML documents, which i parse with apache's Xerces parser... I am trying to delete certain elements and replace them with others, but none of the api's allow this the closes i have come is replacing attributes of elements....

    Answered in crosspost.
    http://forum.java.sun.com/thread.jspa?threadID=638156

  • Search and replace in powershell using wildcards

    Hi
    I'm trying to figure out how to replace a some random (ish) text, in a text string with a defined piece of text using Powershell.
    The text I want to replace is always between the same two words but the actual text varies from device to device.
    Lets say the text line is 
    Server this bit of text varies Language
    I want to replace the text between "Server" and "Language" with "it will always say this"
    I want to write something like this
    replace('Server'*'Language','Server it will always say this Language')
    so whatever is between Server and language is replaced with "it will always say this".
    I realise I've not got the regular expression correct. Can anyone help?
    Cheers
    Alex

    If you're replacing the line then you can replace all of the line with your new text. So for example you'd assign the line you want to a variable and replace it with a variable containing your new line.
    Take a look at this Blog post :
    http://blogs.technet.com/b/heyscriptingguy/archive/2011/03/21/use-powershell-to-replace-text-in-strings.aspx

  • How to comment the xml tags using java

    Iam using a xml file i want to comment some of the tags in that file

    And your quesion is? Did you parse it into a Document and do you want to write a changed version into another file?

  • Problems in creating xml tags using java

    i had analysed the xmlnode builder class but i am unable to learn what is the functions of that class.
    so please send me a sample coding to create the following output.
    i need this kind of output.
    <?xml version="1.0"?>
    <tree>
    <node id="acc" text="Accounts" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="1" text="Liabilites" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="5" text="Capital" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="L5" text="Gods A/c" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    </contents>
    </node>
    <node id="10" text="Current Liablities" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    <node id="11" text="Cash On Hand" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="L11" text="Cash" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    </contents>
    </node>
    <node id="12" text="Bank Balance" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="L12" text="ICICI" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    </contents>
    </node>
    </contents>
    </node>
    <node id="2" text="Asset" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="6" text="Fixed Asset" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2"/>
    </contents>
    </node>
    <node id="3" text="Expenses" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="15" text="Direct Expenses" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2">
    <contents>
    <node id="8" text="Purchase" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2"/>
    </contents>
    </node>
    <node id="16" text="InDirect Expenses" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2">
    <contaents>
    <node id="L16" text="Staff Welfare" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2"/>
    </contaents>
    </node>
    </contents>
    </node>
    <node id="4" text="Income" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="13" text="Direct Income" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2">
    <contents>
    <node id="7" text="Sales" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2"/>
    </contents>
    </node>
    <node id="14" text="InDirect Income" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con2"/>
    </contents>
    </node>
    </contents>
    </node>
    <node id="inv" text="Inventory" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="1" text="Raw Material" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1">
    <contents>
    <node id="I1" text="Pigments" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    </contents>
    </node>
    <node id="2" text="Intermediate" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    <node id="3" text="Work In Process" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    <node id="4" text="Finised Goods" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    <node id="5" text="Packing Materials" cImage="tree/images/book.gif" oImage="tree/images/bookopen.gif" contextid="con1"/>
    </contents>
    </node>
    </tree>

    Unless you are using some special tag library or something, SQL is not, as far as I've ever seen, going to handle while loops within the statements. You want to create the table, then you have to create the CREATE statement string
    String c = "CREATE TABLE [dbo].[tblNewTable] (";
    for(int x = 0; x < vFieldFruitVector.size(); x++) {
       c += vFieldFruitVector.get(x) + " char 50 COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL";
    c += ")";
    int res = stmt.executeUpdate(c);

  • Search And Replace Patter VI

    I'm struggling with using the search and replace patter to replace a number of substring matches within a string, can anyone help and tell me what am I doing worng? Not an expert in regexps
    I'm basically trying to replace all the matches for "NONE","none" or "normal" with "OK within the "1NONE2none3normal4" string
    Thanks
    Solved!
    Go to Solution.

    From the help on for the "Match Patern" VI: "This function is similar to the Search and Replace Pattern VI. The Match Pattern function gives you fewer options for matching strings but performs more quickly than the Match Regular Expression function. For example, the Match Pattern function does not support the parenthesis or vertical bar (|) characters." The "Search and Replace Pattern.vi" uses Match Pattern internally.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • 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

  • Catalog manger "search and replace " using xml script

    Hi ,
    we have renamed 6 rpd columns names in rpd & alias is not removed yet .In catalog manager i can search and replace using string .But it takes lot time as they are stored in different reports , which are existing . I am trying to use xml script for replacing them.I got sample script from help file for single column . can anyone help for doing that for multiple strings.I will provide with my inputs .
    my inputs:
    <?xml version="1.0" encoding="utf-8"?>
    <actions>
    <action command="textReplace" oldValue="column 1 " newValue="column one" ignoreCase="true"/>
    <action command="textReplace" oldValue="column 2" newValue="column two" ignoreCase="true"/>
    <action command="textReplace" oldValue="column 3" newValue="column three" ignoreCase="true"/>
    </actions>
    please correct me .

    Given xml content looks okay but just in case check this oldValue="column 1 ", there is additional space at the end.
    I would suggest to extract Analysis report (.csv) using Catalog Manager and find out the list of reports based on those columns.
    This would help you learn with list of reports based on report owners, and then go for the fixing those reports.
    If you go by xml replace you never know the affected reports and you may not confirm until report owners come back to you with issues.
    This might take little bit time but your changes based on proper doc.
    Let me know updates, if helps mark
    Edited by: Srini VEERAVALLI on Feb 19, 2013 3:21 PM

  • Xml search and replace for 'Session Variables' in column title view

    Hi Experts,
    I have around 10 reports where measure column titles are displayed based the session variable.
    Below is the syntax I have used in the column title
    @{biServer.variables['NQ_SESSION.VariableName']}
    Now I would like to replace the above syntax with some static text. To do this, I am trying to use the xml search and replace feature in the catalog manager.
    For some reason, catalog manager is unable to find the syntax in the xml file. I have tried using escape character also for the apostrophe by using &apos, but no luck.
    Any pointers on how to replace the text?
    Thanks

    Using Analysis get the xml conversion for @{biServer.variables['NQ_SESSION.VariableName']} from Advanced tab's xml code
    use this code to find in catalog manager, if you able to find then go for search and replace option.
    I think this should work for you.

  • GUI Based tool for search and replace using regular expression

    Hi,
    I have developed this small tool which can be used for search and replace in multiple files using reqular expressions.
    Features:
    1. Full regular expression
    2. GUI based with Highlighted results
    3. Preview for replace available
    4. Pure Java based.
    5. Its like unix sed and grep
    Please visit below site for download/more information :
    http://sourceforge.net/projects/regexsearchrepl/
    Thanks,
    Hitesh Viseria

    I agree with you, it cannot compete grep/sed/awk combination. I couldnt find anything even close to grep/sed for windows which will also have a preview and most important, free. That is what made me write this tool. I am trying to
    improve its performance and more features like history etc.
    Any suggestions on additional features are most welcome.

  • Search and Replace using wild characters

    I have a bit of a problem on my hands while dealing jdom and xml. I am parseing an xml response from a service. The issue is that it contains an element with a colon. Nothing I can do about the service so I have to deal with it. I know I could use DOM and s on but I have chose to use jdom for a couple of reasons. What I am planning on doing is removing the colon in the element names with some sort of search and replace. The problem is that the there could be up to 500 element names with a numeric value. The element name looks like the following ns1:Point, ns2:Point, ns3:Point, and so on. JDom will not handle this so I would like it the element name to look ns1Point, ns2Point, etc. I have the xml returned from the service in a string. Is there any way I can do a search and replace given the above information. Thanks in advance

    Silverfoot wrote:
    I realize that it seperates the name space. The namespace for the element is different than ns1. Maybe I am missing something though
    Using JDOM, I navigate my way through the xml using getChild(elementname, namespace). When i get to ns1:Point, i use the same namespace as previous elements. Are you suggesting that ns1 is another namespace. In that case I would use a second name space to the Point element.I think you're missing a whole lot, actually. You don't seem to know much about namespaces. For a start you're apparently making the beginner error of assuming that the namespace prefix declares the namespace. And this idea:
    What I am planning on doing is removing the colon in the element names with some sort of search and replace.is just wrong. I would suggest you go off and find a tutorial (or a chapter in your XML book) about namespaces.

  • 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

Maybe you are looking for

  • Report Performance plase help

    Hi MY report is base on the view wihich is a based on 10 unions of select statments. I am trying to improve the performance. I am planing to remove the view completelty and base a report on the SQL. Please see below ffor view structure create view XY

  • Query Browser not available in Dashboards appl !?

    Hello, We installed SAP BO Dashboards 4.1 SP2 (14.1.2.1121) and want to use universe queries in the dashboard. The workspace feature "Query Browser" is empty. We don't get the icons to logon to BOXI (to universe). Is this an installation issue? What

  • Top Level Navigation Problem

    Hi guys, recently, I ran into something really strange. The Top Level Navigation (TLN) became faulty. If the user clicks on certain entries in First Level Navigation or Second Level Navigation the content area is not loaded properly. The content area

  • Pacman -Syu after a major makeworld

    so its like this a made a makewordl to oficcial an unoficcial packages them one day e made pacman -Syu just in case new stuf appeared after its finishes it askes if i want to upgrade some pakages e say Y but its stops the upgrade . the error is somet

  • Export comments as csv

    I'm using my Comments field to store multiple genres. eg. Rock, Pop, Metal, Classical How can I export the comments field to a .csv file, then create a new Smart Playlist with "Comment - contains - Rock"? Is this possible? Obviously not straight from