Java XML: using the DOM with StAX to create a document

I am using StAX to create an XML document using XMLStreamWriter .

However, there are parts of my document where it is difficult to make XMLStreamWriter method calls one by one, and it would be easier to create a small fragment of the document using the DOM and then write it.

I know how to use the DOM, but here my question is: is there an easy way to take an Element object and write it before XMLStreamWriter ?

Perhaps I can figure out how to β€œconnect” the two methods, but it seems that it will be tiring, and something should already be there. (another option seems trivial: http://blogs.oracle.com/venu/entry/constructing_dom_using_stax_writers )

+4
source share
2 answers

I don't think I have something that covers the basics (not sure if this will work with namespaces, but it seems to work with a simple DOM node tree):

 public static void writeDomToXmlStreamWriter(Node node, XMLStreamWriter xmlw) throws XMLStreamException { if (node != null) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: { Element element = (Element)node; if (element.getPrefix() != null) xmlw.writeStartElement(element.getPrefix(), element.getLocalName(), element.getNamespaceURI()); else if (element.getNamespaceURI() != null) xmlw.writeStartElement(element.getNamespaceURI(), element.getLocalName()); else if (element.getLocalName() != null) xmlw.writeStartElement(element.getLocalName()); else xmlw.writeStartElement(element.getNodeName()); writeDomAttributesToXmlStreamWriter(element, xmlw); for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) writeDomToXmlStreamWriter(child, xmlw); xmlw.writeEndElement(); } break; case Node.TEXT_NODE: { xmlw.writeCharacters(node.getTextContent()); } } } } private static void writeDomAttributesToXmlStreamWriter(Element element, XMLStreamWriter xmlw) throws XMLStreamException { NamedNodeMap map = element.getAttributes(); for (int L = map.getLength(), i = 0; i < L; ++i) { Node attr = map.item(i); if (attr.getPrefix() != null) xmlw.writeAttribute(attr.getPrefix(), attr.getLocalName(), attr.getNamespaceURI(), attr.getNodeValue()); else if (attr.getNamespaceURI() != null) xmlw.writeAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getNodeValue()); else if (attr.getLocalName() != null) xmlw.writeAttribute(attr.getLocalName(), attr.getNodeValue()); else xmlw.writeAttribute(attr.getNodeName(), attr.getNodeValue()); } } 
+2
source

You can use javax.xml.transform libraries. You could convert the DOM wrapped in a DOMSource to a StAXResult wrapping your stream entry.

This is essentially a descriptive version of the approach described here:

0
source

Source: https://habr.com/ru/post/1342366/


All Articles