Reputation: 1001
I have an application that sends an xml string to an output stream. Before writing the content to the output stream I have to make sure that content in text node(content in node value) doesn't exceed a fixed length. For this I have written a sample code to grab the text node content which can help me to do the content validation. But I'm afraid that this sample code is effective since it's taking about .2 secs when I run it eclipse profiler(TPTP). I would like to find out if there are any better ways to do this to improve the performance. Below is the sample code.
StringWriter stringWriter = new StringWriter();
stringWriter.write("<node src='something'>nodetext goes here</node>");
InputSource src = new InputSource(new StringReader(stringWriter.toString()));
try {
Element doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
System.out.println(doc.getChildNodes().getLength());
Node n = doc.getChildNodes().item(0);
System.out.println(n.getNodeValue());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 0
Views: 276
Reputation: 163322
You will get a vast performance improvement by reusing the DocumentBuilderFactory - creating the factory involves searching the classpath. Reusing the DocumentBuilder will probably help as well. However, the overall approach of creating XML as a string, parsing it, and then serailizing it again seems intrinsically inefficient and I haven't really understood your explanation of why it's necessary.
Upvotes: 1
Reputation: 3424
Use the SAX parser instead of the DOM. See this article for an example.
Upvotes: 0