Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 6181019
Votes 13
Synopsis REGRESSION: org.w3c.dom.Element.toString() no longer returns the xml document
Category jaxp:dom
Reported Against 1.3
Release Fixed 1.3.1(jwsdp_1.6)
State 10-Fix Delivered, bug
Priority: 3-Medium
Related Bugs
Submit Date 19-OCT-2004
Description
FULL PRODUCT VERSION :
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-b64)
Java HotSpot(TM) Client VM (build 1.5.0-b64, mixed mode, sharing)


ADDITIONAL OS VERSION INFORMATION :
Linux unununium 2.4.21-20.EL #1 Wed Aug 18 20:58:25 EDT 2004 i686 i686 i386 GNU/Linux


EXTRA RELEVANT SYSTEM CONFIGURATION :
$ cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 15
model           : 3
model name      :  customer (R) Pentium(R) 4 CPU 2.80GHz
stepping        : 3
cpu MHz         : 2793.051
cache size      : 1024 KB
fdiv_bug        : no
hlt_bug         : no
f00f_bug        : no
coma_bug        : no
fpu             : yes
fpu_exception   : yes
cpuid level     : 5
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm
bogomips        : 5570.56


A DESCRIPTION OF THE PROBLEM :
In java 1.4.2 org.w3c.dom.Element.toString() returned the xml element as a String.  In 5.0 it no longer does.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Compile and run the sample program included with java 5.0.  Compile and run it with java 1.4.2 to see correct output.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
<datacenterlist>
  <datacenterinfo id="0" naddrs="1" nnodes="1" ismaster="0">
    < customer  ipaddr="192.168.100.27:26000" />
  </datacenterinfo>
</datacenterlist>

ACTUAL -
[datacenterlist: null]


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class XMLToStringTest
{
   String xml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
      "<!DOCTYPE datacenterlist>\n" +
      "<datacenterlist>\n" +
      "  <datacenterinfo id=\"0\" naddrs=\"1\" nnodes=\"1\" ismaster=\"0\">\n" +
      "    < customer  ipaddr=\"192.168.100.27:26000\"/>\n" +
      "  </datacenterinfo>\n" +
      "</datacenterlist>\n";

   public XMLToStringTest()
   {
      try
      {
         Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
            new InputSource( new StringReader( xml ) ) );
         Element root = doc.getDocumentElement();
         System.out.println( root.toString() );
      }
      catch( Exception e )
      {
         e.printStackTrace( System.err );
      }
   }

   public static final void main( String[] args )
   {
      new XMLToStringTest();
   }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Write a program that iterates over all Nodes in an Document, and generates the string representation of them.

Release Regression From : 1.4.2
The above release value was the last known release where this 
bug was known to work. Since then there has been a regression.
  xxxxx@xxxxx   10/19/04 05:03 GMT
Work Around
N/A
Evaluation
note that this appears as a regression yet there actually is no Element.toString() defined by the spec, it was an implementation, Crimson, detail that allowed this to work.
DOM L3 has a LSSerializer, use it to serialize nodes for toString() behavior.
  xxxxx@xxxxx   2005-05-25 00:52:12 GMT
Comments
  
  Include a link with my name & email   

Submitted On 09-NOV-2004
ScottWPalmwe
Another workaround is to use a transformer to write the XML to a byte array and then construct a String from the UTF-8 bytes. (be sure to specify the encoding)


Submitted On 12-NOV-2004
ScottWPalmwe
This problem is rather serious for applications that used toString() in Java 1.4 write simple XML files.  How did this get overlooked?  And why does it have so few votes?  Isn't this a total disaster that warrants a quick fix?


Submitted On 30-JAN-2005
sidthesloth
I got a solution and looks like this:

----------------- SOURCE --------------------------

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

public class XMLtest {

  private Document document;
  private File testFile;
  private PrintWriter pw;

  public XMLtest() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
      testFile = new File("test.xml");
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(testFile);
      test();
    }
    catch (SAXParseException spe) {
      System.out.println("Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
      System.out.println("  " + spe.getMessage());
      Exception x = spe;
      if (spe.getException() != null)
        x = spe.getException();
      x.printStackTrace();
    }
    catch (SAXException sxe) {
      Exception x = sxe;
      if (sxe.getException() != null)
        x = sxe.getException();
      x.printStackTrace();
    }
    catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    }
    catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

  
  private String getNode(Node node) {
      String Node = "<" + node.getNodeName().toString();
      if (node.hasAttributes()) {
                for (int m = 0; m < node.getAttributes().getLength();m++) {
                    Node += " " + node.getAttributes().item(m).getNodeName();
                    Node += "=


Submitted On 30-JAN-2005
sidthesloth
private String getNode(Node node) {
      String Node = "<" + node.getNodeName().toString();
      if (node.hasAttributes()) {
                for (int m = 0; m < node.getAttributes().getLength();m++) {
                    Node += " " + node.getAttributes().item(m).getNodeName();
                    Node += "='" + node.getAttributes().item(m).getNodeValue() + "'";
                }
              }
      Node += ">";
      if (!node.hasChildNodes()) {
          Node += "</" + node.getNodeName().toString() + ">";
      }
      return Node;
  }
  
  private String getAllNodes(Node node) {
      String document = "";
      if (node.hasChildNodes()) {
        for (int i = 0; i<node.getChildNodes().getLength();i++) {
            document += getNode(node.getChildNodes().item(i));
            document += getAllNodes(node.getChildNodes().item(i));
            if (i == node.getChildNodes().getLength()-1) {
                document += "</" + node.getNodeName().toString() + ">";
            }
        }
      }
      return document;
  }
  
  
  private String docToString() {
      String newDocument = "";
      Node node = document.getDocumentElement();
      newDocument += "<" + node.getNodeName().toString() + ">";
      if (node.hasAttributes()) {
          for (int i =0; i<node.getAttributes().getLength(); i++) {
              newDocument += node.getAttributes().item(i).getLocalName().toString();
          }
      }
      
      newDocument += getAllNodes(node);
             
      System.out.println(newDocument);
      return newDocument;
  } 
 
  
  private void test() {
    try {
      pw = new PrintWriter(new FileWriter(new File("output.xml")));
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
    
    pw.println(docToString());
    pw.close();

  }

  public static void main(String[] args) {
    new XMLtest();
  }

}

---------- END SOURCE --------------------------

for more complex xml-files this could consist some bugs! This programm just reads an xml-file and writes the content to another xml-file.
This program was tested under JDK 1.4.2_04 and 1.5.0_01 .


Submitted On 06-APR-2005
RichardFrederiksen
This bug is a real pain. I just got a related bug submission from a customer today and thought I was losing my mind. I wouldn't mind it so much if I thought there was any utility to the new string representation but its definitely not obvious to me.


Submitted On 19-MAY-2005
dgherrig
This is a real killer issue, I am very suprised this has not been fixx in the 03 updates, 


Submitted On 25-MAY-2005
ScottWPalmwe
Why does the bug say fixed in 1.3.1 when the bug didn't exist until Java 5??  Based on the evaluation I can't even tell if the bug was really fixed, or if it is a 


Submitted On 26-MAY-2005
edtyrrill
This implementation detail that they declined to fix is used all over in my application.  If you don't want people to use functionality you depricate it, not remove it.  Please fix this bug.


Submitted On 22-JUN-2005
Xibolba
In what release will this be available - 1.5.x, 1.6?


Submitted On 10-DEC-2005
sidthesloth
now ever better:

   private String getNode(Node node) {
      String Node = "<" + node.getNodeName().toString();
      if (node.hasAttributes()) {
                for (int m = 0; m < node.getAttributes().getLength();m++) {
                    Node += " " + node.getAttributes().item(m).getNodeName();
                    Node += "='" + node.getAttributes().item(m).getNodeValue() + "'";
                }
              }
      Node += ">";
      return Node;
  }


  private String getAllNodes(Node node) {
      String document = "";
      document += getNode(node);
      if (node.hasChildNodes()) {
        for (int i = 0; i<node.getChildNodes().getLength(); i++) {
            document += getAllNodes(node.getChildNodes().item(i));
            if (i == node.getChildNodes().getLength()-1) {
                document += "</" + node.getNodeName() + ">";
            }
        }
      } else {
          document += "</" + node.getNodeName() + ">";
      }
      return document;
  }


Just use the getAllNodes(Node) and you´ll get an String with  the xml-document containing Node and all of it´s childnodes


Submitted On 05-JUN-2008
CarlG
All of the posted DIY solutions are going to have issues with entities, I think. The LSSerializer mentioned in the evaluation is much better, but not obvious how to use. Try:

public static String nodeToString(Node node){
    DOMImplementation impl = node.getOwnerDocument().getImplementation();
    DOMImplementationLS factory = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = factory.createLSSerializer();
    return serializer.writeToString(node);
}



PLEASE NOTE: JDK6 is formerly known as Project Mustang