Solved

Deleting tags from XML file

Posted on 2003-12-10
20
903 Views
Last Modified: 2013-11-19
I have this XML file that I need to delete from. I currently have this working by copying it to StringBuffer and then using indexOf to find the position then use the delete(). It's quite ugly. I will love to delete it using XML way of some sort  e.q removeChild() or something better, but I don't know how. here is a small copy of the file, the file is normally bigger than this. I need to delete any occurence of Kona tag. I put comment line on the line to delete.
I am doing this inside my java class, the project name comes like "Tasman". Need to load the file, delete some tags and write back to the file. Please help!
I indicated what I want to delete with <!-- I am trying to delete from here -----> and
 <!-- to here  -----> . I have two set of delete to do.



<config>

 <queryset name="Clar Queries" type="clar">
     <query name="TASMANDefectsEntry">
         <description>Snapshot Defect Summary from Clarify Status Change Table</description>
               <sql name="ClarifyDefectsEntry" startweek="74" project="TASMAN"/>
                  <tablename>TASMANDefectsEntry</tablename>
      </query>

<!-- I am trying to delete from here ----->
     <query name="KONADefectsSnapshot">
            <description>Snapshot Defect Summary from Clarify showing substatus</description>
             <sql name="ClarifyDefectsSnapshot" startweek="83" project="KONA"/>
              <tablename>KONADefectsSnapshot</tablename>
      </query>
       <query name="KONADefectsEntry">
       <description>Snapshot Defect Summary from Clarify Status Change Table</description>
        <sql name="ClarifyDefectsEntry" startweek="83" project="KONA"/>
         <tablename>KONADefectsEntry</tablename>
   </query>
<!-- to here  ----->

       <query name="LL_MozartDefectsSnapshot">
              <description>Snapshot Defect Summary from Clarify showing substatus</description>
                  <sql name="ClarifyDefectsSnapshot" startweek="200" project="LL_Mozart"/>
                  <tablename>LL_MozartDefectsSnapshot</tablename>
       </query>
<!--EndOfNameSset-->
      </queryset>
      <queryset name="TASMANReports" type="report">
            <shorttitle>TASMAN</shorttitle>
            <title>TASMAN Defect Reports</title>
       <description>TASMAN Reports including current snapshot, weekly change and  History.</description>
      </queryset>

<!-- I am trying to delete from here ----->
      <queryset name="KONAReports" type="report">
            <shorttitle>KONA</shorttitle>
            <title>KONA Defect Reports</title>
            <description>KONA Reports including current snapshot, weekly change and History.</description>

            <query name="Snapshot">
                  <description>This is a snapshot of the KONA project defects grouped by status.</description>
                  <sql>select * from KONADefectsSnapshot</sql>
                  <shorttitle>Snapshot</shorttitle>
                  <title>KONA Defects Status Snapshot</title>
            </query>

            <!-- The following history reports are week by week, but not cumulative -->

            <query name="HistoryCreated">
                  <description>This is a historical report for the KONA project showing bugs created per week.</description>
                  <sql name="HistoryCreate" table="KONA_history_created"/>
                  <title>KONA Defects History : Bug Creation </title>
                  <shorttitle>History : Creation</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="HistoryDeferred">
                  <description>This is a historical report for the KONA project showing bugs deferred changes per week.</description>
                  <sql name="HistoryDeferred" table="KONA_history_deferred"/>
                  <title>KONA Defects History : Bug Defers</title>
                  <shorttitle>History : Defers</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="HistoryOpened">
                  <description>This is a historical report for the KONA project showing bugs opened per week.</description>
                  <sql name="HistoryOpened" table="KONA_history_open"/>
                  <title>KONA Defects History : Bug Opened</title>
                  <shorttitle>History : Opened</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="HistoryClosed">
                  <description>This is a historical report for the KONA project showing bugs closed per week.</description>
                  <sql name="HistoryClosed" table="KONA_history_closed"/>
                  <title>KONA Defects History : Bug Closures</title>
                  <shorttitle>History : Closures</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <!-- The following cumulative reports are based on the history reports but sum over the weeks -->
            <query name="CumulativeOpen">
                  <description>This is a cumulative trend report for the KONA project showing bugs open per week. Open bugs are calculated by summing Create and Re-Open events and subtracting Close and Duplicate Close events in the activity log.</description>
                  <sql name="CumulativeOpen" table="KONA_total_open"/>
                  <title>KONA Defects Cumulative Trend : Open </title>
                  <shorttitle>Cumulative : Open</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="CumulativeDeferred">
                  <description>This is a cumulative trend report for the KONA project showing bugs Deferred per week.</description>
                  <sql name="CumulativeDeferred" table="KONA_total_deferred"/>
                  <title>KONA Defects Cumulative Trend : Deferred </title>
                  <shorttitle>Cumulative : Deferred</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="CumulativeCreated">
                  <description>This is a cumulative trend report for the KONA project showing bugs Created per week.</description>
                  <sql name="CumulativeCreated" table="KONA_total_created"/>
                  <title>KONA Defects Cumulative Trend : Createded </title>
                  <shorttitle>Cumulative : Created</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="CumulativeClosed">
                  <description>This is a cumulative trend report for the KONA project showing bugs Closed per week.</description>
                  <sql name="CumulativeClosed" table="KONA_total_closed"/>
                  <title>KONA Defects Cumulative Trend : Closed </title>
                  <shorttitle>Cumulative : Closed</shorttitle>
                  <graph type="linegraph"/>
            </query>

            <query name="CumulativeSummary">
                  <description>This is a cumulative trend report for the KONA project. It shows Open, Deferred and Closed queries.</description>
                  <sql name="CumulativeSummary" table="KONA_summary"/>
                  <shorttitle>Cumulative : Summary</shorttitle>
                  <title>KONA Defects Cumulative Trend</title>
                  <graph type="linegraph"/>
            </query>
      </queryset>
<!-- to here ----->      

            <queryset name="TASMANReports" type="report">
                  <shorttitle>TASMAN</shorttitle>
                  <title>TASMAN Defect Reports</title>
                  <description>TASMAN Reports including current snapshot, weekly change and History.</description>
     
            </queryset>


<!--EndOfQuerySet-->

</config>
0
Comment
Question by:newtosvg
  • 10
  • 5
  • 3
  • +2
20 Comments
 
LVL 6

Expert Comment

by:PeterCiuffetti
ID: 9916530
If you read the XML into a dom, if it a relatively trivial matter to find all the query nodes with a name attr containing some value and then to remove each one:

// JAXP classes
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
// DOM classes
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

Document dom = null;
DocumentBuilderFactory dfactory;
DocumentBuilder docBuilder;

try {
            // Set up the JaxP Parser
      dfactory = DocumentBuilderFactory.newInstance();
      dfactory.setNamespaceAware(true);
      docBuilder = dfactory.newDocumentBuilder();
            // Get the input file into a DOM
      dom = docBuilder.parse(new File("input.xml"));
            
            // Get all the query elements in the DOM
      NodeList queryNodes = dom.getElementsByTagName("query");
      for (int i = 0; i < queryNodes.getLength(); i++) {
            Element queryNode = (Element) queryNodes.item(i);

            // Remove each query node if the name attr contains 'KONA'
            if (queryNode.hasAttribute("name")) {
                  Node nameAttr = queryNode.getAttributes().getNamedItem( "name" );
                  String name = nameAttr.getNodeValue();
                  if ( name.indexOf("KONA") != -1 ) {
                        Node queryParent = query.getParentNode();
                        queryParent.removeChild( queryNode );
                  }
            }
      }  
} catch ( Exception ex ) {
      System.out.println("Exception removing query node " + ex );
}

You can then output your modified dom using a XML Serializer:

import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.apache.xml.serialize.OutputFormat;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;

/**
 * Utility class to serialize a DOM to an OutputStream
 */
public class DOMSerializer
{
    /**
     * Serializer the supplied DOM
     * @param Document - the DOM to serialize
     * @param OutputStream - stream to serialize to
     * @param boolean - true if XML entities are escaped
     * @param String[] - elements in which not to escape entities null if escapeEntities is true
     * @param boolean - true if pretty print in, use only if going to file
     */
    public static void serialize( Document dom,
                                  OutputStream output,
                                  boolean escapeEntities,
                                  String[] nonEscapingElements,
                                  boolean prettyPrint ) throws IOException
    {
        // Set up output format depending on options
        OutputFormat format = new OutputFormat( dom, null, prettyPrint );
        // Always preserve whitespace
        format.setPreserveSpace( true );
        if( escapeEntities )
        {
            format.setNonEscapingElements( nonEscapingElements );
        }

        // Now create a serializer, give it the output
        XMLSerializer serializer = new XMLSerializer( format );
        serializer.setOutputCharStream( new OutputStreamWriter(output, "UTF-8"));
        // Do it
        serializer.serialize( dom );

    }

0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9919505
hm...how about using XSLT for this?
for instance ilke this:
.................
<xsl:template match="query[starts-with(@name,'KONA'"]> <!-- select query with name starts with KONA-->
          <!-- do nothing here, cause we don't want it in output -->
 </xsl:template>
.....................

may be it will be more simply and readable to transform your xml with xsl like above, and get output without tags you don't want to.
0
 
LVL 9

Expert Comment

by:sparkplug
ID: 9920331
I agree with dualsoul that XSLT would be the appropriate technology to use here. It is both simpler and more flexible. The full XSLT would be:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

      <xsl:template match="@*|node()">
            <xsl:copy>
                  <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
      </xsl:template>

      <!-- select query with name starts with KONA-->
            <!-- do nothing here, cause we don't want it in output -->
      <xsl:template match="query[starts-with(@name,'KONA'"] />
 
 </xsl:stylesheet>

>S'Plug<
0
 

Author Comment

by:newtosvg
ID: 9920656
Question for Peter.
Node queryParent = query.getParentNode();  // the value query is not declare. What should it be.
Also I was getting an error message like this" The method serialize cannot be declared static, statics method can only be declared in a static or top level type" I the method inside my class. Do I have to put it in in it own class? and if so where and how will I call it inside deleteProject that I called the top part code?

Dualsoul. I don't know xsl at all. I want to do the delete in my java class.

Thanks guys
 
0
 
LVL 6

Expert Comment

by:PeterCiuffetti
ID: 9920899
Yep, sorry.  it should be:

Node queryParent = queryNode.getParentNode();

The XML serializer code I posted was just an example utility I've used in my own code.  The key function it demostrates is the use of XMLSerializer.  If you want to use the util, then yes, put it in its own file called DOMSerializer.java

Then you can call it like this:

import com.you.DOMSerializer;

        FileOutputStream output = new FileOutputStream("output.xml");
        // Serialize the DOM to this output, do not escape entities, do not pretty print.
        DOMSerializer.serialize( dom, output, false, null, false );

This code (and the previously posted code) will result in a UTF-8 output file.  If you want another encoding, then the DOMSerialiser output format needs to change.  And if you want indented ouput, set the last param to true.

Pete
0
 

Author Comment

by:newtosvg
ID: 9921156
This is the code that I have, and I get this error message. The error message is longer than this, I just copy two lines. Nothing was deleted in the config.xml and no data in the output file.
 
"javax.servlet.ServletException: org.apache.xerces.util.NamespaceSupport.reset(Lorg/apache/xerces/util/SymbolTable;)V
      at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
"

public void deleteProj(String projectName){
try {
   String target = "C:/Liz/config.txt";
  // Set up the JaxP Parser
  dfactory = DocumentBuilderFactory.newInstance();
  dfactory.setNamespaceAware(true);
  docBuilder = dfactory.newDocumentBuilder();
  // Get the input file into a DOM
 //  dom = docBuilder.parse(new File("input.xml"));
//  dom = docBuilder.parse(new File("C:/Program Files/Apache Group/Tomcat 4.1/webapps/stats/config.xml"));
  dom = docBuilder.parse(new File(resource.CONFIGFILE));
     
  // Get all the query elements in the DOM
     NodeList queryNodes = dom.getElementsByTagName("query");
    for (int i = 0; i < queryNodes.getLength(); i++) {
    Element queryNode = (Element) queryNodes.item(i);
  // Remove each query node if the name attr contains 'KONA'
    if (queryNode.hasAttribute("name")) {
   Node nameAttr = queryNode.getAttributes().getNamedItem( "name" );
   String name = nameAttr.getNodeValue();
//  if ( name.indexOf("KONA") != -1 ) {
      if ( name.indexOf("projectName") != -1 ) {
          Node queryParent = queryNode.getParentNode();
          queryParent.removeChild( queryNode );
      }
  }
   //Call to DOMSerializer after the for loop
    FileOutputStream output = new FileOutputStream(target);
  // Serialize the DOM to this output, do not escape entities, do not pretty print.
   DOMSerializer.serialize( dom, output, false, null, false );
    }  
  } catch ( Exception ex ) {
      System.out.println("Exception removing query node " + ex );
}

  }
 
0
 

Author Comment

by:newtosvg
ID: 9921468
I had a lot of print out and queryNode is null everytime.
0
 

Author Comment

by:newtosvg
ID: 9921739
if ( name.indexOf("projectName") != -1 )
projectName is without the quote
0
 
LVL 6

Expert Comment

by:PeterCiuffetti
ID: 9921992
??? getElementsByTagName is not ever supposed to return null.  It either returns an empty node list (getLength() = 0) or it returns a list of nodes matching the name.  In either case, if there are no query nodes, the for loop should not be entered.  If there are queryNodes, then queryNode should not be null.  

I think you will need to post the whole stack trace.  I suspect you are not even getting as far as the dom document parse.  I would also expect that if anything went wrong, you'd get a printout of the exception from the catch block.  I suspect that the above code is not producing the exception.  Please look in the Tomcat-4.1/logs server log and report back if there are any exceptions there. If you want to more easily isolate the problem and you are running a local instance of Tomcat, then just close tomcat, delete the logs files, restart and retest the page.  Then see what the logs say...

Pete
0
 
LVL 26

Expert Comment

by:rdcpro
ID: 9922488
Just a third party observation...

newtosvg says:

"I don't know xsl at all. I want to do the delete in my java class."

I'd say it's high time to learn XSLT.  XML tranformations are what it's designed for, and the complete transform was posted by S'Plug.  Probably took him less than 2 minutes to write.  A few lines of Java to invoke the transform, and you'd have been done by now.  

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
Transformer trans;
TransformerFactory factory = TransformerFactory.newInstance();
String stylesheet = "file://stylesheets/mystylesheet.xsl";
String xml_doc = "file://xml_docs/myXMLdoc.xml";

trans = factory.newTransformer(new StreamSource(stylesheet));
trans.transform(new StreamSource(xml_doc), new StreamResult(System.out));


And I'll bet dollars to doughnuts that XSLT will be much faster to execute than equivalen DOM code.  And it will be MUCH easier to extend to other changes in the future...

Regards,
Mike Sharp

0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:newtosvg
ID: 9922652
I am running Tomcat locally, I deleted all the old logs as you specified and check the new log, the is no exception in the log. Here is the some out the output from Tomcat : Thanks for all your help

Before loop queryNodes: org.apache.xerces.dom.DeepNodeListImpl@1909385
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="TASMANDefectsEntry"
Before 2nd if value of name: TASMANDefectsEntry
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="LL_MozartDefectsSnapshot"
Before 2nd if value of name: LL_MozartDefectsSnapshot
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="LL_MozartDefectsEntry"
Before 2nd if value of name: LL_MozartDefectsEntry
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="LL_GeckoDefectsSnapshot"
Before 2nd if value of name: LL_GeckoDefectsSnapshot
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="LL_GeckoDefectsEntry"
Before 2nd if value of name: LL_GeckoDefectsEntry
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="KONADefectsSnapshot"
Before 2nd if value of name: KONADefectsSnapshot
Project Name index: KONADefectsSnapshot
QueryParent value : [queryset: null]
After loop queryNode value: [query: null]
After first if: [query: null]
This nameATTR value: name="Snapshot"
0
 

Author Comment

by:newtosvg
ID: 9923074
Mike Sharp,
If I do have a lot of time, I will go and learn XSLT, but I don't.
I am trying to put this in Production by tomorrow.

If I do save this as mystylesheet.xsl, how do I pass in the name KONA as a variable from my java Bean class? If you or S'Plug can help, that will be great. At least I can understand Peter's code from what I have in Java aspect. A complete code will be great. Thanks.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

     <xsl:template match="@*|node()">
          <xsl:copy>
               <xsl:apply-templates select="@*|node()"/>
          </xsl:copy>
     </xsl:template>

     <!-- select query with name starts with KONA-->
           <!-- do nothing here, cause we don't want it in output -->
     <xsl:template match="query[starts-with(@name,'KONA'"] />
 
 
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9923206
>If I do save this as mystylesheet.xsl, how do I pass in the name KONA as a variable from my java Bean class?

it's easy, oyu should set up stylesheet parameter to your transformer class:
(just rdcpro code improven)
.......................................
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
Transformer trans;
TransformerFactory factory = TransformerFactory.newInstance();
String stylesheet = "file://stylesheets/mystylesheet.xsl";
String xml_doc = "file://xml_docs/myXMLdoc.xml";
//!!! your parameter to search here !!!
String matchString="KONA";

trans = factory.newTransformer(new StreamSource(stylesheet));
//!!! set up stylesheet parameter
trans.setParameter("SearchString",matchString);
trans.transform(new StreamSource(xml_doc), new StreamResult(System.out));
.......................................

and change XSLT a bit:
....................................
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<!-- stylesheet parameter here -->
      <xsl:param name="SearchString" />  
     <xsl:template match="@*|node()">
          <xsl:copy>
               <xsl:apply-templates select="@*|node()"/>
          </xsl:copy>
     </xsl:template>

     <!-- select query with name starts with SearchString-->
           <!-- do nothing here, cause we don't want it in output -->
     <xsl:template match="query[starts-with(@name,$SearchString]" />
 
 </xsl:stylesheet>
..................................

hope it helps
0
 

Author Comment

by:newtosvg
ID: 9923996
I saved the xsl and I have this method in my java class.
Got this error message:"Exception removing query node javax.xml.transform.TransformerConfigurationExcept
ion: javax.xml.transform.TransformerConfigurationException: javax.xml.transform.
TransformerException: javax.xml.transform.TransformerException: Expected ,, but
found: ]"

  public void deleteProj(String projectName){
      String target = "C:/Liz/config.txt";

      Transformer trans;
      TransformerFactory factory = TransformerFactory.newInstance();
      String stylesheet = "file://stylesheets/C:/Liz/mystylesheet.xsl";
      String xml_doc = "file://xml_docs/C:/Program Files/Apache Group/Tomcat 4.1/webapps/stats/config.xml";
//        !!! your parameter to search here !!!
      String matchString=projectName;
      try
      {
      trans = factory.newTransformer(new StreamSource(stylesheet));
//        !!! set up stylesheet parameter
      trans.setParameter("SearchString",matchString);
      trans.transform(new StreamSource(xml_doc), new StreamResult(System.out));
  } catch ( Exception ex ) {
         System.out.println("Exception removing query node " + ex );
  }
 
  } //end deleteProj      
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9926675
year...sorry we've forgot to close ) and ] in stylesheet, here is the full version of XSLT and Java code, i've tested it -> all works.
Note, i took a look to your question again, and found, that you wanted to remove <queryset>  with name, starting woth 'KONA' too, so i've added one line to XSLT to do it.

....................................
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<!-- stylesheet parameter here -->
     <xsl:param name="SearchString" />  
     <xsl:template match="@*|node()">
          <xsl:copy>
               <xsl:apply-templates select="@*|node()"/>
          </xsl:copy>
     </xsl:template>

     <!-- select query and quesryset with name starts with SearchString-->
           <!-- do nothing here, cause we don't want it in output -->
     <xsl:template match="query[starts-with(@name,$SearchString)]" />
     <xsl:template match="queryset[starts-with(@name,$SearchString)]" />
 </xsl:stylesheet>
....................................

....................................
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class sample{
      public static void main(String args[]){
            String target = "config.txt";
            Transformer trans;
            TransformerFactory factory = TransformerFactory.newInstance();
            String stylesheet = "mystylesheet.xsl";
            String xml_doc = "config.xml";
            //       !!! your parameter to search here !!!
            String matchString="KONA";
            try {
                  trans = factory.newTransformer(new StreamSource(stylesheet));
                  //       !!! set up stylesheet parameter
                  trans.setParameter("SearchString",matchString);
                  trans.transform(new StreamSource(xml_doc), new StreamResult(System.out));
            }
            catch ( Exception ex ) {
                  System.out.println("Exception removing query node " + ex );
            }
      }
}
....................................

Hope it helps.
0
 

Author Comment

by:newtosvg
ID: 9931775
Well almost there. It deleted the nodes all right if I put the  new StreamResult()  into a different file and I can see the new xml. But I want to reload the new xml in the same xml file. (i.e read from config.xml to delete and reload config.xml back after the delete.) right now, all the data in config.xml are deleted

The "resource.CONFIGFILE" is the file I am reading from and is the same file I want to write to.
Thanks for all your help dualsoul, I really appreciate it

public void deleteProj(String projectName){
  Transformer trans;
  TransformerFactory factory = TransformerFactory.newInstance();
  String stylesheet = "file://stylesheets/" +resource.STYLESHEET;

  String xml_doc = "file://xml_docs/" +resource.CONFIGFILE ;
//        !!! your parameter to search here !!!
  String matchString=projectName;
  try {
      trans = factory.newTransformer(new StreamSource(stylesheet));
        //       !!! set up stylesheet parameter
           trans.setParameter("SearchString",matchString);
        trans.transform(new StreamSource(xml_doc), new StreamResult(resource.CONFIGFILE));
   }
  catch ( Exception ex ) {
  System.out.println("Exception removing query node " + ex );
}
 
  }

0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9933763
> But I want to reload the new xml in the same xml file
you can not read and write same file at the same time.

so, you can use some work around to update your config.xml.
For instance you can transform to some temporary file, and then copy it instead of your original config.xml, see code snippet:

.....................................................
import java.io.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class sample{
      public static void main(String args[]){
            String target = "config.txt";
            Transformer trans;
            TransformerFactory factory = TransformerFactory.newInstance();
            String stylesheet = "mystylesheet.xsl";
            String xml_doc = "config.xml";
            //       !!! your parameter to search here !!!
            String matchString="KONA";

//some workaround here            
            //our config xml file
            File config=new File("config.xml");
            
            //temporary file for transformation
            //you can use File.createTempFile() instead, to use OS temp dir for it
            File temp=new File("config.tmp");

            try {
                  trans = factory.newTransformer(new StreamSource(stylesheet));
                  //       !!! set up stylesheet parameter
                  trans.setParameter("SearchString",matchString);
                  trans.transform(new StreamSource(xml_doc), new StreamResult(temp));

//swap temp and original files
            //remove original config.xml
                  config.delete();                  
            //rename temp to original file
                  temp.renameTo(config);                  
            }
            catch ( Exception ex ) {
                  System.out.println("Exception removing query node " + ex );
            }
      }
}
.....................................................

, or you can transfrom to String, using StreamWriter for it, and then write this String to your config.xml, but it just the same as above, only it can cause out of memory for huge xml files.

Hope it helps.
0
 

Author Comment

by:newtosvg
ID: 9935459
I will try this on Monday and get back to you. I was thinking about copying it to a  StringBuffer and then right it back to config.xml, but I like your swapping better.
Thanks.
0
 
LVL 15

Accepted Solution

by:
dualsoul earned 250 total points
ID: 9935508
>I will try this on Monday and get back to you.
as you wish :), i've tested it before posting, it's all with my code :)

> I was thinking about copying it to a  StringBuffer and then right it back to config.xml, but I like your swapping better.
as i mention if copy huge xml file to StringBuffer you can get out-of-memory, and if you're using  File streams you can process xml files with every size.
0
 

Author Comment

by:newtosvg
ID: 9943226
Thanks dualsoul. It works fine now.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now