Example #1
0
    def __init__(self, xsl_path, **params):
        from javax.xml.transform import URIResolver
        from javax.xml.transform import TransformerFactory
        from javax.xml.transform.stream import StreamSource
        from java.io import FileInputStream

        xsl_path = os.path.abspath(xsl_path)
        xsl_base = os.path.dirname(xsl_path)

        xsl_fis = FileInputStream(xsl_path)

        xsl_source = StreamSource(xsl_fis)

        class BaseURIResolver(URIResolver):

            def __init__(self, base):
                self.base = base

            def resolve(self, href, base):
                path = os.path.join(self.base, href)
                path = os.path.abspath(path)
                fis = FileInputStream(path)
                return StreamSource(fis)

        uri_resolver = BaseURIResolver(xsl_base)

        xslt_factory = TransformerFactory.newInstance()
        xslt_factory.setURIResolver(uri_resolver)

        self.transformer = xslt_factory.newTransformer(xsl_source)
        for k, v in params.items():
            self.transformer.setParameter(k, unicode(v))
Example #2
0
	def toFile(self, doc, filename):
		source = DOMSource(doc)
		file = File(filename);
		result = StreamResult(file);
		xformer = TransformerFactory.newInstance().newTransformer();
		
		xformer.transform(source, result);
Example #3
0
    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)
Example #4
0
  def transformReport(self,stylesheet,xml,output,params):
    from java.io import FileInputStream
    from java.io import FileOutputStream
    from java.io import ByteArrayOutputStream

    from javax.xml.transform import TransformerFactory
    from javax.xml.transform.stream import StreamSource
    from javax.xml.transform.stream import StreamResult

    self.xsl   = FileInputStream("%s" % stylesheet)
    self.xml   = FileInputStream("%s" % xml)
    self.html  = FileOutputStream("%s" % output)

    try:
      self.xslSource   = StreamSource(self.xsl)
      self.tfactory    = TransformerFactory.newInstance()
      self.xslTemplate = self.tfactory.newTemplates(self.xslSource)
      self.transformer = self.xslTemplate.newTransformer()

      self.source = StreamSource(self.xml)
      self.result = StreamResult(self.html)

      for self.key,self.value in params.items():
        self.transformer.setParameter(self.key, self.value)

      self.transformer.transform(self.source, self.result)

    finally:
      self.xsl.close()
      self.xml.close()
      self.html.close()
Example #5
0
    def __init__(self, xsl_path, **params):
        from javax.xml.transform import URIResolver
        from javax.xml.transform import TransformerFactory
        from javax.xml.transform.stream import StreamSource
        from java.io import FileInputStream

        xsl_path = os.path.abspath(xsl_path)
        xsl_base = os.path.dirname(xsl_path)

        xsl_fis = FileInputStream(xsl_path)

        xsl_source = StreamSource(xsl_fis)

        class BaseURIResolver(URIResolver):
            def __init__(self, base):
                self.base = base

            def resolve(self, href, base):
                path = os.path.join(self.base, href)
                path = os.path.abspath(path)
                fis = FileInputStream(path)
                return StreamSource(fis)

        uri_resolver = BaseURIResolver(xsl_base)

        xslt_factory = TransformerFactory.newInstance()
        xslt_factory.setURIResolver(uri_resolver)

        self.transformer = xslt_factory.newTransformer(xsl_source)
        for k, v in params.items():
            self.transformer.setParameter(k, unicode(v))
Example #6
0
    def transformReport(self, stylesheet, xml, output, params):
        from java.io import FileInputStream
        from java.io import FileOutputStream
        from java.io import ByteArrayOutputStream

        from javax.xml.transform import TransformerFactory
        from javax.xml.transform.stream import StreamSource
        from javax.xml.transform.stream import StreamResult

        self.xsl = FileInputStream("%s" % stylesheet)
        self.xml = FileInputStream("%s" % xml)
        self.html = FileOutputStream("%s" % output)

        try:
            self.xslSource = StreamSource(self.xsl)
            self.tfactory = TransformerFactory.newInstance()
            self.xslTemplate = self.tfactory.newTemplates(self.xslSource)
            self.transformer = self.xslTemplate.newTransformer()

            self.source = StreamSource(self.xml)
            self.result = StreamResult(self.html)

            for self.key, self.value in params.items():
                self.transformer.setParameter(self.key, self.value)

            self.transformer.transform(self.source, self.result)

        finally:
            self.xsl.close()
            self.xml.close()
            self.html.close()
 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()
Example #8
0
 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()
Example #9
0
    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())
Example #10
0
def writeDom(doc):
    try:
        # set up a transformer
        transfac = TransformerFactory.newInstance()
        trans = transfac.newTransformer()
        trans.setOutputProperty(OutputKeys.ENCODING, "utf-8")
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no")
        trans.setOutputProperty(OutputKeys.INDENT, "yes")
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
        
        sw1 = StringWriter()
        result = StreamResult(sw1)
        source = DOMSource(doc)
        trans.transform(source, result)
        xmlString = sw1.toString()
        print xmlString
    except Exception, e:
        print e
Example #11
0
  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())
Example #12
0
def transform(xmldoc, xslt=config.defualt_xslt):
    '''
    Runs the transform from the specified xslt against the provided
    document.  The transformer is only loaded on the first run and
    then kept in memory for re-use.
    '''
    global _transform

    if _transform is None:
        tFactory = TransformerFactory.newInstance()
        tFactory.setAttribute('http://saxon.sf.net/feature/licenseFileLocation', '/etc/saxon-license.lic')
        try:
            _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt)))
        except TransformerConfigurationException, tce:
            print tce
            print '*' * 70
            print 'This is likely that your license file for saxon is '\
                  'missing or that there is a genuine error in the XSLT'
def xslt_compile(xsl_path):
    from javax.xml.transform import URIResolver
    from javax.xml.transform import TransformerFactory
    from javax.xml.transform.stream import StreamSource
    from javax.xml.transform.stream import StreamResult
    from java.io import FileInputStream
    from java.io import FileOutputStream
    import os.path

    xsl_path = os.path.abspath(xsl_path)
    xsl_base = os.path.dirname(xsl_path)

    xsl_fis = FileInputStream(xsl_path)

    xsl_source = StreamSource(xsl_fis)

    class BaseURIResolver(URIResolver):

        def __init__(self, base):
            self.base = base

        def resolve(self, href, base):
            path = os.path.join(self.base, href)
            path = os.path.abspath(path)
            fis = FileInputStream(path)
            return StreamSource(fis)

    uri_resolver = BaseURIResolver(xsl_base)

    xslt_factory = TransformerFactory.newInstance()
    xslt_factory.setURIResolver(uri_resolver)

    transformer = xslt_factory.newTransformer(xsl_source)

    def transform(inp_path, out_path):
        inp_path = os.path.abspath(inp_path)
        out_path = os.path.abspath(out_path)
        inp_fis = FileInputStream(inp_path)
        out_fos = FileOutputStream(out_path)
        inp_source = StreamSource(inp_fis)
        out_result = StreamResult(out_fos)
        transformer.transform(inp_source, out_result)
        return dict()
    return transform
Example #14
0
def xslt_compile(xsl_path):
    from javax.xml.transform import URIResolver
    from javax.xml.transform import TransformerFactory
    from javax.xml.transform.stream import StreamSource
    from javax.xml.transform.stream import StreamResult
    from java.io import FileInputStream
    from java.io import FileOutputStream
    import os.path

    xsl_path = os.path.abspath(xsl_path)
    xsl_base = os.path.dirname(xsl_path)

    xsl_fis = FileInputStream(xsl_path)

    xsl_source = StreamSource(xsl_fis)

    class BaseURIResolver(URIResolver):
        def __init__(self, base):
            self.base = base

        def resolve(self, href, base):
            path = os.path.join(self.base, href)
            path = os.path.abspath(path)
            fis = FileInputStream(path)
            return StreamSource(fis)

    uri_resolver = BaseURIResolver(xsl_base)

    xslt_factory = TransformerFactory.newInstance()
    xslt_factory.setURIResolver(uri_resolver)

    transformer = xslt_factory.newTransformer(xsl_source)

    def transform(inp_path, out_path):
        inp_path = os.path.abspath(inp_path)
        out_path = os.path.abspath(out_path)
        inp_fis = FileInputStream(inp_path)
        out_fos = FileOutputStream(out_path)
        inp_source = StreamSource(inp_fis)
        out_result = StreamResult(out_fos)
        transformer.transform(inp_source, out_result)
        return dict()

    return transform
Example #15
0
def transform(xmldoc, xslt=config.defualt_xslt):
    '''
    Runs the transform from the specified xslt against the provided
    document.  The transformer is only loaded on the first run and
    then kept in memory for re-use.
    '''
    global _transform

    if _transform is None:
        tFactory = TransformerFactory.newInstance()
        tFactory.setAttribute(
            'http://saxon.sf.net/feature/licenseFileLocation',
            '/etc/saxon-license.lic')
        try:
            _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt)))
        except TransformerConfigurationException, tce:
            print tce
            print '*' * 70
            print 'This is likely that your license file for saxon is '\
                  'missing or that there is a genuine error in the XSLT'
def transform(xlst, xmldoc, docuuid):
    '''
    Runs the transform from the specified xslt against the provided
    document.  The transformer is only loaded on the first run and
    then kept in memory for re-use.
    '''
    global _transform
    global _errors
    global _count

    if _transform is None:
        tFactory = TransformerFactory.newInstance()
        try:
            _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt)))
        except TransformerConfigurationException, tce:
            print tce
            print '*' * 70
            print 'This is likely that your license file for saxon is '\
                  'missing or that there is a genuine error in the XSLT'
            sys.exit(1)
Example #17
0
def transform(xlst, xmldoc, docuuid):
    '''
    Runs the transform from the specified xslt against the provided
    document.  The transformer is only loaded on the first run and
    then kept in memory for re-use.
    '''
    global _transform
    global _errors
    global _count

    if _transform is None:
        tFactory = TransformerFactory.newInstance()
        try:
            _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt)))
        except TransformerConfigurationException, tce:
            print tce
            print '*' * 70
            print 'This is likely that your license file for saxon is '\
                  'missing or that there is a genuine error in the XSLT'
            sys.exit(1)
Example #18
0
    def _transform(self):
        try:
            input = FileInputStream(self.xsl)
            xslSource = StreamSource(input)
            xslTemplate = TransformerFactory.newInstance().newTemplates(xslSource);
            transformer = xslTemplate.newTransformer()

            output = ByteArrayOutputStream()
            result = StreamResult(output)

            source = StreamSource(FileInputStream(self.sourceXml))
            transformer.transform(source, result)

            f = open(self.targetXml, 'w')
            f.write(output.toString())

            return True
        except:
            print ("Something went wrong when trying to transform the XML.  Please be sure jython is properly installed and configured.")
            return False
Example #19
0
  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())
Example #20
0
    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())
Example #21
0
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()
Example #22
0
def transform(xmldoc, xslt=config.defualt_xslt):
    '''
    Runs the transform from the specified xslt against the provided
    document.  The transformer is only loaded on the first run and
    then kept in memory for re-use.
    '''
    global _transform

    if _transform is None:
        tFactory = TransformerFactory.newInstance()
        tFactory.setAttribute('http://saxon.sf.net/feature/licenseFileLocation', '/etc/saxon-license.lic')
        # JJ: not sure I have the right syntax here, but can Saxon be set to continue on error?
        #10/21.  agreed to try and run a pass against a "minimal transform" in the event that an error is thrown here.  Will work on XSLT
        tFactory.setAttribute(FeatureKeys.RECOVERY_POLICY, new Integer(Controller.RECOVER_SILENTLY));
        #
        try:
            _transform = tFactory.newTransformer(StreamSource(JavaFile(xslt)))
        except TransformerConfigurationException, tce:
            print tce
            print '*' * 70
            print 'This is likely that your license file for saxon is '\
                  'missing or that there is a genuine error in the XSLT'
Example #23
0
    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)
Example #24
0
	- 2 xml source
	- 3 xml output
 
"""
 
from java.io import File;
from javax.xml.transform import Transformer;
from javax.xml.transform import TransformerFactory;
from javax.xml.transform.stream import StreamResult;
from javax.xml.transform.stream import StreamSource;
from java.io import StringWriter;
import os
import sys
 
xslt = File(sys.argv[1])
tFactory = TransformerFactory.newInstance()
transformer = tFactory.newTransformer(StreamSource(xslt))
writer = StringWriter();
out = transformer.transform(
							StreamSource(File(
								sys.argv[2]
								)),
					        StreamResult(
					        	File(sys.argv[3])
					        )
					       )
out2 = transformer.transform(
							StreamSource(File(
								sys.argv[2]
								)),
					         StreamResult(writer)
Example #25
0
from java.lang import System
from java.io import File
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()
Example #26
0
 def saveXMLDoc(self, doc, xmlPath):
     transformerFactory = TransformerFactory.newInstance()
     transformer = transformerFactory.newTransformer()
     source = DOMSource(doc)
     result = StreamResult(File(xmlPath))
     transformer.transform(source, result)
Example #27
0
'''

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>
	<Terminal><Name>DelaySetValueFeedback</Name><Value>0.000000</Value></Terminal>
</Response>
def transform(source, stylesheet, result, parameters):
    transformer = TransformerFactory.newInstance().newTransformer(stylesheet)
    for (p, v) in parameters: transformer.setParameter(p, v)
    transformer.transform(source, result)