如何将 XML 转换为文本

How to transform XML to text

根据我之前的问题 (),我现在有一个结构良好的 XML 文档,就像这样..

<?xml version="1.0" encoding="UTF-8"?>
<root>
<employee id="1" reportsTo="1" title="CEO">
    <employee id="2" reportsTo="1" title="Director of Operations">
        <employee id="3" reportsTo="2" title="Human Resources Manager" />
    </employee>
</employee>
</root>

现在我需要像这样将其转换为 javascript..

var treeData = [
{
"name": "CEO",
"parent": "null",
"children": [
  {
    "name": "Director of Operations",
    "parent": "Top Level",
    "children": [
      {
        "name": "Human Resources Manager",
        "parent": "Level 2: A"
      }
   ]
  }
]
}
];

我已经开始编写 XSLT,目前看起来像这样..

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="text" omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="root">
    <xsl:apply-templates select="employee" />
</xsl:template>

<xsl:template match="employee">
    <xsl:param name="eId" select="@id" />
    <xsl:param name="eReports" select="@reportsTo" />
    <xsl:param name="eTitle" select="@title" />
    <xsl:value-of select="concat( $eTitle, ' and ', $eId )" />      
    <xsl:apply-templates select="employee" />
</xsl:template>

</xsl:stylesheet>

但是当我应用转换(通过 pythons lxml 库)时,我收到消息 "None"。 (如果有帮助,这是我正在使用的 lxml 命令...)

dom = ET.parse("input.xml")
xslt = ET.parse("transform.xslt")
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))

我知道我的 XSLT 还远未完成,但为什么我没有得到 any 输出?至少我不应该打印职位名称吗?

编辑:OP 包含他的 Python 代码后更新。

你的问题是 lxml.etree.tostring.write 方法只对 XML 有意义,对 output method="text" 的 XSLT 结果没有意义,它可能没有一个像 XML 这样的根元素。由于某些令人困惑的原因,函数 do 有一个 method= 关键字参数,但它没有做任何有用的事情。

这是你应该做的:

import lxml.etree as etree
data = etree.parse('data.xml')
transform = etree.XSLT(etree.parse('txt.xslt'))
res = transform(data)
bytes(res)
b'\nCEO and 1Director of Operations and 2Human Resources Manager and 3\n'

如果您对真实世界的示例感兴趣,I recently made a patch.