How to transform XML to text

心已入冬 提交于 2019-12-11 19:33:40

问题


Following on from my earlier question (how to transform XML?), I now have a nicely structured XML doc, like this..

<?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>

Now I need to convert it to javascript like this..

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

I've started writing an XSLT, which currently looks like this..

<?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>

But when I apply the transform (via pythons lxml library), I get the message "None". (In case it helps, here's the lxml command I'm using...)

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

I know my XSLT is nowhere near complete, but why aren't I getting any output? Shouldn't I at least be getting the job title printed?


回答1:


Edit: updated now that OP's included his Python code.

Your problem is that lxml.etree.tostring and also the .write method are only meaningful on XML, not on an XSLT result with output method="text" which might not have a single root element like XML does. For some confusing reason, the functions do have a method= keyword argument but it does not do anything useful.

This is what you should do:

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'

If you're interested in a real world example, I recently made a patch.



来源:https://stackoverflow.com/questions/31282067/how-to-transform-xml-to-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!