
com.bytekast.sweettalk.util.DomUtil.groovy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sweet-talk Show documentation
Show all versions of sweet-talk Show documentation
A Sensible NetSuite SuiteTalk API wrapper
The newest version!
package com.bytekast.sweettalk.util
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.CompileStatic
import groovy.transform.Memoized
import groovy.xml.DOMBuilder
import groovy.xml.XmlUtil
import groovy.xml.dom.DOMCategory
import org.codehaus.groovy.tools.xml.DomToGroovy
import org.w3c.dom.Element
import javax.xml.bind.JAXBContext
import javax.xml.bind.Marshaller
@Singleton
class DomUtil {
private JsonSlurper slurper = new JsonSlurper()
@CompileStatic
String xmlToGroovyMarkup(String xml) {
def dom = DOMBuilder.newInstance().parseText(xml?.trim())
def writer = new StringWriter()
def converter = new DomToGroovy(new PrintWriter(writer))
converter.print(dom)
writer.toString()
}
@CompileStatic
String JAXBModelToXml(def obj) {
JAXBContext context = JAXBUtil.instance.createContext(obj.class)
Marshaller jaxbMarshaller = context.createMarshaller()
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE)
def writer = new StringWriter()
jaxbMarshaller.marshal(obj, writer)
writer.toString()
}
@Memoized
@CompileStatic
Element xmlStringToDocument(String xml) {
DOMBuilder.parse(new StringReader(xml), false, false).documentElement
}
@Memoized
String xpath(Element document, String xpath) {
use(DOMCategory) {
document.xpath(xpath)
}
}
@Memoized
String xpath(String xml, String xpath) {
use(DOMCategory) {
xmlStringToDocument(xml).xpath(xpath)
}
}
@CompileStatic
String prettyPrintXml(String xml) {
XmlUtil.serialize(xml)
}
@CompileStatic
String xmlToJson(String xml) {
JsonOutput.prettyPrint(org.json.XML.toJSONObject(xml).toString())
}
Map xmlToMap(String xml) {
slurper.parseText(JsonOutput.prettyPrint(org.json.XML.toJSONObject(xml).toString()))
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy