0

My transformation stylesheet file contains:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <cities>
            <xsl:for-each select="cities/country">
                <city name="{@capital}" isCapital="true"/>
            </xsl:for-each>
        </cities>
    </xsl:template>
</xsl:stylesheet>

My python code:

import os
import xml.etree.ElementTree as ET
from saxonpy import PySaxonProcessor

def main():
    print('starting code...')
    source_XML = '''
        <data>
            <country name="Denmark" capital="Copenhagen"/>
            <country name="Germany" capital="Berlin"/>
            <country name="France" capital="Paris"/>
        </data>
    '''
    parentroot = ET.fromstring(source_XML)
    children = list(parentroot)

    # create individual raw xmls
    cnt = 0
    for child in children:
        cnt = cnt + 1
        childroot = ET.Element("cities")
        childroot.append(child)
        tempfile_tree = ET.ElementTree(childroot)
   
        # tempfile = "C:\\pythonProject\\stackoverflow\\tmp.xml"
        # tempfile = "C:\\gaga\\tmp.xml"
        # tempfile = os.path.abspath("tmp.xml")
        tempfile = "tmp.xml"

        transformedfile = f"output_{cnt}.xml"
        with open(tempfile, 'wb') as f:
            tempfile_tree.write(f, encoding='utf-8', xml_declaration=True)

        try:
            with PySaxonProcessor(license=False) as proc:
                proc.set_cwd(os.getcwd())
                xsltproc = proc.new_xslt30_processor()
                xsltproc.transform_to_file(source_file=tempfile,
                                           stylesheet_file="transformer.xsl",
                                           output_file=transformedfile)
                print(f"{transformedfile} has been created.")
        except Exception as e:
            print(e)

if __name__ == "__main__":
    main()

my problem

I have saxonpy imported. I'm trying to run saxonc's transform_to_file() inside a loop. I'm unable to get the transformed output files. Depending on what I set for tempfile, i get

        #   I/O error reported by XML parser processing C:\pythonProject\stackoverflow\░╚╒E ⌂:
        #   unknown protocol: c. Caused by java.net.MalformedURLException: unknown protocol: c

or

Content is not allowed in prolog
(this is definitely not the case, I checked the tempfile with a hexeditor)

or no error but output file containing only:

        # <?xml version="1.0" encoding="UTF-8"?>
        # <cities/>

but also correct outputs (but I can't reproduce it anymore).

Note: I disabled MAX_PATH when installing python 3.10. Note: using Pycharm with poetry venv

5
  • With xml files, shouldn't it be with open(tempfile, 'w') as f:?
    – ewokx
    May 24, 2022 at 8:42
  • Thanks for the suggestio, @ewong, but this gives me TypeError: write() argument must be str, not bytes
    – woodduck
    May 24, 2022 at 8:47
  • What if you removed the encoding=... part? (I probably should defer to others more knowledgeable than I)
    – ewokx
    May 24, 2022 at 8:48
  • @ewong, tried it. that made no difference (besides, I need it)
    – woodduck
    May 24, 2022 at 8:50
  • This does look like an encoding issue, but saxonpy is using an old version of SaxonC. Is it possible you can upgrade to the official version of SaxonC which also has a Python API.
    – ond1
    May 24, 2022 at 11:11

3 Answers 3

1

Using SaxonC 11.3 I managed to run the python script above with the minor change:

from saxonpy import PySaxonProcessor

Replaced with:

from saxonc import *

I got the output:

starting code...
output_1.xml has been created.
output_2.xml has been created.
output_3.xml has been created.

These files all have the following content:

<?xml version="1.0" encoding="UTF-8"?>
<cities/>

As I workaround I replaced transform_to_file with transform_to_string:

                valueStr = xsltproc.transform_to_string(source_file=tempfile,
                                           stylesheet_file="transformer.xsl")
                                           #output_file=transformedfile)
                print(valueStr)

This does produce the correct output:

starting code...
source in transformFiletoString=tmp.xml stylsheet=transformer.xsl
<?xml version="1.0" encoding="UTF-8"?>
<cities>
   <city name="Copenhagen" isCapital="true"/>
</cities>

output_1.xml has been created.

<?xml version="1.0" encoding="UTF-8"?>
<cities>
   <city name="Berlin" isCapital="true"/>
</cities>

output_2.xml has been created.

<?xml version="1.0" encoding="UTF-8"?>
<cities>
   <city name="Paris" isCapital="true"/>
</cities>

output_3.xml has been created.
4
  • Thanks for the reply but that is still not the correct output. It's one of the false results I mentioned (I made a typo, i wrote <root/> originally). The correct, transformed output (for the third iteration) should be<?xml version="1.0" encoding="UTF-8"?> <cities> <city name="Paris" isCapital="true"/> </cities>
    – woodduck
    May 24, 2022 at 11:59
  • also, I'm using saxonpy because I need to package everything into an executable and I don't think that's possible without (?).
    – woodduck
    May 24, 2022 at 12:00
  • As I workaround I replaced transform_to_file with transform_to_string. Which you can try for saxonpy. I am investigating if there is a bug against transform_to_file
    – ond1
    May 24, 2022 at 13:10
  • thanks, I'm already using transform_to_string() elsewhere in my app and that works fine. But I also need to use transform_to_file(). Either with a file as input or an xml string as input. In fact, this question is a workaround for stackoverflow.com/questions/72360664/…. If all else fails, I suppose I could output it to a string and then create a file from it.
    – woodduck
    May 24, 2022 at 15:48
1

I have now installed SaxonC 1.2.1

I got the correct output with the following python script:

import os
import xml.etree.ElementTree as ET
from saxonpy import *

def main():
    print('starting code...')
    source_XML = '''
        <data>
            <country name="Denmark" capital="Copenhagen"/>
            <country name="Germany" capital="Berlin"/>
            <country name="France" capital="Paris"/>
        </data>
    '''
    parentroot = ET.fromstring(source_XML)
    children = list(parentroot)

    # create individual raw xmls
    try:
        with PySaxonProcessor(license=False) as proc:
            proc.set_cwd(os.getcwd())
            xsltproc = proc.new_xslt30_processor()
            cnt = 0
            for child in children:
                cnt = cnt + 1
                childroot = ET.Element("cities")
                childroot.append(child)
                tempfile_tree = ET.ElementTree(childroot)
   
                # tempfile = "C:\\pythonProject\\stackoverflow\\tmp.xml"
                # tempfile = "C:\\gaga\\tmp.xml"
                # tempfile = os.path.abspath("tmp.xml")
                tempfile = "tmp.xml"

                transformedfile = f"output_{cnt}.xml"
                with open(tempfile, 'wb') as f:
                    tempfile_tree.write(f, encoding='utf-8', xml_declaration=True)

                    xsltproc.set_property("s",tempfile)
                    xsltproc.transform_to_file(source_file=tempfile,
                                           stylesheet_file="transformer.xsl",
                                           output_file=transformedfile)
                    #print(valueStr)
                    print(f"{transformedfile} has been created.")
    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()

7
  • This was a linux machine. What platform are you running saxonpy
    – ond1
    May 24, 2022 at 15:27
  • I'm on Windows, but this didn't work for me. I got 'saxonc.PyXslt30Processor' object has no attribute 'set_property'
    – woodduck
    May 24, 2022 at 15:52
  • Sorry please remove that line: xsltproc.set_property("s",tempfile)
    – ond1
    May 24, 2022 at 17:22
  • after removing that line I still get the incomplete output: <?xml version="1.0" encoding="UTF-8"?> <cities/>
    – woodduck
    May 24, 2022 at 18:03
  • 1
    Yes it has the same functionality. The apply_templates_return_file is designed for XSLT30
    – ond1
    May 24, 2022 at 19:43
0

With Apply_templates_returning_file() it works:

import os
import xml.etree.ElementTree as ET
from saxonpy import PySaxonProcessor

def main():
    print('starting code...')
    source_XML = '''
        <data>
            <country name="Denmark" capital="Copenhagen"/>
            <country name="Germany" capital="Berlin"/>
            <country name="France" capital="Paris"/>
        </data>
    '''
    parentroot = ET.fromstring(source_XML)
    children = list(parentroot)

    try:
        with PySaxonProcessor(license=False) as proc:
            proc.set_cwd(os.getcwd())
            xsltproc = proc.new_xslt30_processor()
            xslt30_transformer = xsltproc.compile_stylesheet(stylesheet_file="transformer.xsl")

            cnt = 0
            for child in children:
                cnt = cnt + 1
                childroot = ET.Element("cities")
                childroot.append(child)
                tempfile_tree = ET.ElementTree(childroot)

                tempfile = "tmp_1234567890ABCDEFGHIJKLMNOP.xml"
                transformedfile = f"output_{cnt}.xml"

                with open(tempfile, 'wb') as f:
                    tempfile_tree.write(f, xml_declaration=True)

                xslt30_transformer.apply_templates_returning_file(source_file=tempfile,
                                                                  output_file=transformedfile)
                print(f"{transformedfile} has been created.")

    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()
4
  • it also works with xdm_node instead of source_file as input (see stackoverflow.com/questions/72360664)
    – woodduck
    May 24, 2022 at 19:34
  • 1
    For speed improvement you can move the new_xslt30_processor and the compile_stylesheet out of the for loop.
    – ond1
    May 24, 2022 at 19:53
  • good call. I edited the code
    – woodduck
    May 24, 2022 at 20:20
  • 1
    The bug in transform_to_file has been fixed on the SaxonC 11 branch. See: saxonica.plan.io/issues/5537
    – ond1
    May 26, 2022 at 9:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.