You are viewing a plain text version of this content. The canonical link for it is here.
Posted to j-users@xerces.apache.org by Ramesh Babu <qq...@yahoo.com> on 2003/02/21 19:52:59 UTC

preserve xml format

Hi,
I'm reading xml file and parsing thru' 
apache Xerces(xerces-1_4_3) DOMParser. 
I serialize the xml and I want to save into the file.

my xml,
<?xml version="1.0" encoding="ISO-8859-1"?>
<Root>
     <Property key="A" cat="door"/>
</Root>

and my code,

import java.io.*;
import org.w3c.dom.*;
import org.apache.xml.serialize.*;
import org.apache.xerces.parsers.DOMParser;

public class XmlWriter {
  private DOMParser domParser;
  private String strFileName;
  private Document doc;
  public XmlWriter(String strFileName) throws
Exception {
    try {
      this.strFileName = strFileName;
      this.domParser = new DOMParser();
      domParser.parse(strFileName);
      doc = domParser.getDocument();
    }
    catch(Exception oEx) {
      System.out.println("\n XML Parse Error.\n" +
oEx);
      throw oEx;
    }
  }

  public String serializeXml() {
    StringWriter sw = new StringWriter();
    OutputFormat format = new OutputFormat();
    format.setIndenting(true);
    format.setLineWidth(0);
    format.setPreserveSpace(true);
    XMLSerializer serializer = new XMLSerializer(sw,
format);

    try {
      serializer.asDOMSerializer();
     
serializer.serialize(this.getDocument().getDocumentElement());
    } catch (Exception ex) {
      System.out.println("[serializeXml()] exception
while serializing" + ex);
    }
    return sw.toString();
  }

  public boolean writeXml(String newXml, String
fileToWrite, boolean append) {
    try {
      BufferedWriter writer = new BufferedWriter( new
FileWriter( fileToWrite, append ) );
      writer.write(newXml);
      writer.flush();
      writer.close();
    } catch(Exception ex) {
      System.out.println("[writeXml()] Exception while
writing" + ex);
      return false;
    }
    return true;
  }

  public Document getDocument() {
    return(doc);
  }

  public static void main(String[] args) {
    String fileName = args[0];
    XmlWriter writer = null;
    try {
      writer = new XmlWriter(fileName);
      String newXml = writer.serializeXml();
      writer.writeXml(newXml, fileName + ".test",
false);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
After executing, the file it looks like

<Property cat="door" key="A" />

Actually attributes are sorted which I don't want.

How do I preserver the old format of the xml ?

Any API I need to use ? any help ?

Thanks. 

__________________________________________________
Do you Yahoo!?
Yahoo! Tax Center - forms, calculators, tips, more
http://taxes.yahoo.com/

---------------------------------------------------------------------
To unsubscribe, e-mail: xerces-j-user-unsubscribe@xml.apache.org
For additional commands, e-mail: xerces-j-user-help@xml.apache.org