File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes XML and Related Technologies and the fly likes Error while compiling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Error while compiling " Watch "Error while compiling " New topic

Error while compiling

Ranch Hand

Joined: Feb 21, 2001
Posts: 63
Hi All,
This is a test java file which parses xml file and return element. When i try to compile it give me error 'class or interface excepted
Document Fragment' .
Do i need to import any other packages. Pls suggest.
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
// Parses a string containing XML and returns a DocumentFragment
// containing the nodes of the parsed XML.
public static DocumentFragment parseXml(Document doc, String fragment) {
// Wrap the fragment in an arbitrary element
fragment = "<fragment>"+fragment+"</fragment>";
try {
// Create a DOM builder and parse the fragment
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document d = factory.newDocumentBuilder().parse(
new InputSource(new StringReader(fragment)));

// Import the nodes of the new document into doc so that they
// will be compatible with doc
Node node = doc.importNode(d.getDocumentElement(), true);

// Create the document fragment node to hold the new nodes
DocumentFragment docfrag = doc.createDocumentFragment();

// Move the nodes into the fragment
while (node.hasChildNodes()) {

// Return the fragment
return docfrag;
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
return null;

Think Big . So shall you become big.
Lasse Koskela

Joined: Jan 23, 2002
Posts: 11962
It might work a bit smoother if you'd put your method inside a class

Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
I agree. Here's the link:
subject: Error while compiling
It's not a secret anymore!