3

I have a problem. I want to convert the string to a xml document. But this code is throw exception:

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl cannot be cast to org.jdom2.Document at ru.unicus.osp.Test.main(Test.java:17)

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jdom2.Document;
import org.xml.sax.InputSource;

public class Test {
    public static void main(String[] args) throws Exception {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
        Document doc = (Document) db.parse(is);
    }
}

Got any ideas?

Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49
viartemev
  • 211
  • 1
  • 4
  • 13

2 Answers2

2

You are mixing two libraries here, DOM, and JDOM.

your current output Document is a JDOM document, it seems, but you are trying to cast a w3 DOM Document instance to be one, and you are failing.

If you want to have a JDOM Document as your output, then your code should likely be:

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new StringReader("<root><node1></node1></root>"));

For a DOM document output, just use a DOM Document (org.w3c.dom.Document) instead of org.jdom2.Document

rolfl
  • 17,539
  • 7
  • 42
  • 76
2

You mixed two libraries here. The simplest thing that can be done is to change the import from:

import org.jdom2.Document;

to

import org.w3c.dom.Document;

So the code should look like:

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class Test {
   public static void main(String[] args) throws Exception {
       DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
       InputSource is = new InputSource();
       is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
       Document doc = (Document) db.parse(is);  
   }
}
Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49