使用python打印xml内容

2024-09-28 18:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用下面的脚本将xml转换为xslt。转换过程完美无瑕。现在,我想将内容写入一个新的xml文件。当我尝试这样做时,我的xml文件中只有一行。然而,当我在控制台打印它时,我得到了多行输出。谁能看出我做错了什么?你知道吗

import lxml.etree as ET


dom = ET.parse("1.xml")
xslt = ET.parse("1.xsl")
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(newdom)
newdom.write("output.xml")

Tags: 文件import脚本内容parse过程astransform
2条回答

看来你已经把所有的东西都写在输出.xml“文件。可以随意发布输出文件的片段,也可以发布输入文件的片段。你知道吗

如果唯一的问题是希望它跨多行构造,而不是一行,那么可以将pretty print标志设置为true。你知道吗

newdom.write("output.xml", pretty_print=True)

输出示例:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <tr>
        <td>.</td>
        <td>.</td>
      </tr>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

这解决了我的问题

with open('output.xml', 'wb') as f:
    f.write(newdom)

相关问题 更多 >