Convert Document object to String object
843834May 21 2004 — edited May 21 2004I want to parse the XML file, and output the string object of XML representation.
I tried to convert Document object to String object, but it is unsuccessful. Anyone knows
what I miss?
Here's the output of this program, which is wrong:
[person: null]
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
/** transform Document object to XML string */
public class ParserTest
{
public static void main(String[] args) throws ParserConfigurationException, SAXException
{
try
{
String xmlFile = "mydoc.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(xmlFile));
Element root = doc.getDocumentElement();
String s = root.toString();
System.out.println(s);
}
catch(IOException e)
{ e.printStackTrace();
}
}
}
//mydoc.xml
<?xml version = "1.0"?>
<person>
<name>Joe</name>
<age>20</age>
</person>