简体   繁体   中英

How can I include a link to XSLT file with Python ElementTree?

I'm trying hard to include my XSLT header in my XML with ElementTree, and I can´t find any information on how to do it.

Here's my Python code:

tree = ET.parse('myfile.xml') #get all tags from this XML document

root = tree.getroot()  #get all elements from each tag

root[0][0].text = "ole"

root[0][1].text = "ole"

tree.write('test_file.xml', encoding='utf-8', method="xml") #write XML file

The only problem is to include this header:

<\\? xml-stylesheet type="text/xsl" href="myfile.xsl" \\?>

Unfortunately xml.etree.ElementTree does not support XSLT (for instance, you can read about write() that method is either xml , text or html ).

Luckily though, you can easily do that if you rely on lxml which adds supports to XSLT

I just found the answer!!!

You need to use lxml instead and this is the new code:

from lxml import etree as ET 

parser = ET.XMLParser(strip_cdata=False) #strip = false to prevent cdata to be removed/ stripped 
tree = ET.parse('myfile.xml', parser) 
root = tree.getroot()  #get all elements from each tag

tag1 = root.find('TAG1')
tag1.find('TAG2').text = 'text change here'

tree.write('test_file.xml', encoding='utf-8', method="xml")

Your XML template (myfile.xml) is like this:

<?xml-stylesheet type="text/xsl" href="your_file.xsl" ?>
<FirstTAG>              
        <TAG1>      
             <TAG2>your text</TAG2>
        </TAG1>
</FirstTAG>

And the new one will be like this:

<?xml-stylesheet type="text/xsl" href="your_file.xsl" ?>
<FirstTAG>              
        <TAG1>      
             <TAG2>text change here</TAG2>
        </TAG1>
</FirstTAG>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM