1

Is it possible to convert nu.XOM.Element to org.w3c.dom.Element?

Am trying to construct XML using XOM APIs. But few of my legacy APIs expects org.w3c.dom.Element. So, I just want to know if I can convert.

Thank You :)

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
jai
  • 21,519
  • 31
  • 89
  • 120

3 Answers3

1

There is the nu.xom.converters.DOMConverter class, which provides a way of translating an entire XOM document into a corresponding DOM document, but you can't do it for individual elements, probably because a W3C Element can't exist without a parent Document.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • I guess its the other way - DOMConverter converts w3c to XOM's. – jai Jun 22 '10 at 11:28
  • @HanuAthena: It does both. There's one method that does XOM->DOM – skaffman Jun 22 '10 at 11:33
  • Am sorry, am not able to figure out which method is that - http://www.xom.nu/apidocs/index.html?nu/xom/converters/DOMConverter.html – jai Jun 22 '10 at 11:41
  • @HanuAthena: It's the fourth method. http://www.xom.nu/apidocs/nu/xom/converters/DOMConverter.html "Translates a XOM nu.xom.Document object into an equivalent org.w3c.dom.Document object." – skaffman Jun 22 '10 at 11:57
  • See answer from @HanuAthena to see how to get the DOMImplementation instance, which is needed for the convert method call. – Kaitsu Mar 13 '13 at 11:58
1

XOM Document:

final nu.xom.Element root = new nu.xom.Element("root");
root.appendChild("Hello World!");
final nu.xom.Document xomDoc = new nu.xom.Document(root);

using DOMConverter:

final DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final DOMImplementation impl = builder.getDOMImplementation();
final Document w3cDoc= DOMConverter.convert(xomDoc, impl);
jai
  • 21,519
  • 31
  • 89
  • 120
  • +1 because instructed how to get the current DOMImplementation, which is needed. I have no idea why XOM itself doesn't do this as the default. – Kaitsu Mar 13 '13 at 11:57
0
public static org.w3c.dom.Document xomToDom(Element elem) {
    try {
        elem = (Element)elem.copy();
        return
        DOMConverter.convert(new Document(elem), 
                DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation());
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}
honzajde
  • 2,270
  • 3
  • 31
  • 36