def tostring(element_or_tree, encoding=None, method='xml', xml_declaration=None, pretty_print=False, with_tail=True, standalone=None, doctype=None, exclusive=False, with_comments=True, inclusive_ns_prefixes=None): if isinstance(element_or_tree, _ElementTree): source = DOMSource(element_or_tree._dom_doc) else: source = DOMSource(element_or_tree._dom_element) outputstream = ByteArrayOutputStream() result = StreamResult(outputstream) transformer = transformfac.newTransformer() if xml_declaration: transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, 'no') else: transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, 'yes') if pretty_print: transformer.setOutputProperty(OutputKeys.INDENT, 'yes') else: transformer.setOutputProperty(OutputKeys.INDENT, 'no') transformer.transform(source, result) if encoding is None: encoding = 'ascii' return outputstream.toString(encoding)
def __call__(self, _input, profile_run=False, **kw): nsmap = dict(xsl='http://www.w3.org/1999/XSL/Transform') output_method = 'xml' output_encoding = 'utf-8' nodes = self.xsl_tree.xpath('xsl:output/@method', namespaces=nsmap) if len(nodes) > 0: output_method = nodes[0] nodes = self.xsl_tree.xpath('xsl:output/@encoding', namespaces=nsmap) if len(nodes) > 0: output_encoding = nodes[0] #print tostring(_input) if isinstance(_input, _ElementTree): doc_source = DOMSource(_input._dom_doc) elif isinstance(_input, _Element): # Xalan-J 2.7.1 does not support a DOMSource from an Element # so we build new document dom_doc = builder.newDocument() dom_root = dom_doc.importNode(_input._dom_element, True) dom_doc.appendChild(dom_root) doc_source = DOMSource(dom_doc) else: raise NotImplementedError() if output_method in ('xml', 'html'): # TODO: for testing outputstream = ByteArrayOutputStream() result = StreamResult(outputstream) self.transformer.transform(doc_source, result) bytes = outputstream.toByteArray() inputstream = ByteArrayInputStream(bytes) try: dom_doc = builder.parse(inputstream) except: import sys sys.stderr.write(bytes.tostring()) raise result_tree = _ElementTree(dom_doc) return result_tree result = DOMResult() self.transformer.transform(doc_source, result) dom_doc = result.getNode() result_tree = _ElementTree(dom_doc) #print tostring(result_tree) return result_tree else: outputstream = ByteArrayOutputStream() result = StreamResult(outputstream) self.transformer.transform(doc_source, result) resultdoc = builder.newDocument() resulttree = _XSLTResultTree(resultdoc) resulttree._text = outputstream.toString(output_encoding) return resulttree
def toFile(self, doc, filename): source = DOMSource(doc) file = File(filename); result = StreamResult(file); xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result);
def __init__(self, xsl_input, extensions=None, regexp=True, access_control=None): if extensions: raise NotImplementedError('extensions is not supported') if access_control: raise NotImplementedError('access_control is not supported') if isinstance(xsl_input, _ElementTree): xsl_tree = xsl_input elif isinstance(xsl_input, _Element): xsl_tree = ElementTree(xsl_input) else: raise ValueError(xsl_input) self.xsl_tree = xsl_tree self.xsl_source = DOMSource(xsl_tree._dom_doc, xsl_tree.docinfo.URL) self.uri_resolver = __URIResolverImpl(xsl_tree) #print tostring(xsl_tree) fac = TransformerFactory.newInstance() fac.setURIResolver(self.uri_resolver) fac = instrument_xalan_transformer_factory(fac) self.transformer = fac.newTransformer(self.xsl_source)
def __toXMLString(self, document): domSource = DOMSource(document) writer = StringWriter() result = StreamResult(writer) tf = TransformerFactory.newInstance() transformer = tf.newTransformer() transformer.transform(domSource, result) return writer.toString()
def test_xsl_dom(self): xsl_dom = docfac.parse(self.xsl_path) # DOMSource with System Id xsl_source = DOMSource(xsl_dom, self.xsl_path) result = transform(xsl_source, src_source) #print result self.assertTrue('world' in result)
def writeXMLfile(self, doc, xmlfile): try: import sys, traceback from java.io import File from javax.xml.transform import TransformerFactory from javax.xml.transform import OutputKeys from javax.xml.transform.stream import StreamResult from javax.xml.transform.dom import DOMSource tranFactory = TransformerFactory.newInstance() aTransformer = tranFactory.newTransformer() aTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") aTransformer.setOutputProperty(OutputKeys.INDENT, "yes") src = DOMSource(doc) dest = StreamResult(File(xmlfile)) aTransformer.transform(src, dest) except: print "exception: %s" % traceback.format_exception(*sys.exc_info())
def printXMLfile(self, doc): try: from javax.xml.transform import TransformerFactory from javax.xml.transform import OutputKeys from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult from javax.xml.transform.dom import DOMSource from java.io import StringWriter xmlInput = DOMSource(doc) xmlOutput = StreamResult(StringWriter()) tranFactory = TransformerFactory.newInstance() aTransformer = tranFactory.newTransformer() aTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") aTransformer.setOutputProperty(OutputKeys.INDENT, "yes") aTransformer.transform(xmlInput, xmlOutput) print xmlOutput.getWriter().toString() except: print "exception: %s" % traceback.format_exception(*sys.exc_info())
def DoXPath (Filename,XPathString): IS = InputSource (FileInputStream (Filename)) df = DocumentBuilderFactory.newInstance() df.setNamespaceAware(1) doc = df.newDocumentBuilder().parse(IS) serializer = TransformerFactory.newInstance().newTransformer() serializer.setOutputProperty (OutputKeys.OMIT_XML_DECLARATION, "yes") nl = XPathAPI.selectNodeIterator (doc,XPathString) n = nl.nextNode() while n: if IsTextNode (n): # Coalesce contiguous text nodes res = [n.getNodeValue()] nn = n.getNextSibling() while (nn): res.append (nn.getNodeValue()) nn = n.getNextSibling() java.lang.System.out (string.join(res,"")) else: serializer.transform (DOMSource(n), StreamResult (OutputStreamWriter (java.lang.System.out))) java.lang.System.out.println() n = nl.nextNode()
from java.io import ByteArrayOutputStream from javax.xml.parsers import DocumentBuilderFactory from javax.xml.transform import TransformerFactory from javax.xml.transform.dom import DOMSource from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult dbfac = DocumentBuilderFactory.newInstance() dbfac.namespaceAware = True docfac = dbfac.newDocumentBuilder() print type(dbfac) transfac = TransformerFactory.newInstance() src_dom = docfac.parse('hello.xml') src_source = DOMSource(src_dom) def unsigned_byte(x): if x < 0: return 256 + x return x def Transformer(xsl_source): transformer = transfac.newTransformer(xsl_source) def transform(src_source): outputstream = ByteArrayOutputStream() dst_result = StreamResult(outputstream) transformer.transform(src_source, dst_result) return ''.join(chr(unsigned_byte(x)) for x in outputstream.toByteArray())
line = rd.readLine(); rd.close(); txt=responseBuilder.toString(); ''' dbf = DocumentBuilderFactory.newInstance() db = dbf.newDocumentBuilder() doc = db.parse(url.openStream()) value = doc.getElementsByTagName('Terminal').item(1).item( 1).getFirstChild().getNodeValue() lg = float(value) print lg source = DOMSource(doc) file = File("/tmp/aaa.xml") result = StreamResult(file) xformer = TransformerFactory.newInstance().newTransformer() xformer.transform(source, result) ''' <?xml version="1.0" encoding="UTF-8" standalone="no"?> <Response> <Terminal> <Name>FundamentalEnableFeedback</Name> <Value>1</Value> </Terminal> <Terminal><Name>LoopGainFeedback</Name><Value>79</Value> </Terminal><Terminal><Name>HarmPhaseShiftFeedback</Name><Value>39754</Value></Terminal> <Terminal><Name>FundPhaseShiftFeedback</Name><Value>42977</Value></Terminal>