【发布时间】:2020-01-12 17:34:05
【问题描述】:
我正在使用 python3、lxml-library 和 XSLT 将 XML 转换为 JSON。在运行我的代码时,我不断收到XSLTParseError,但我不确定如何继续前进。
示例 XML 消息:
<SOAP-ENV:Body>
<ns0:BookStore xmlns:ns0="http://www.example.com/xsd/books">
<ns0:Book>
<ns0:Title>The Power of Now</ns0:Title>
<ns0:Author>Vivek Ranadive</ns0:Author>
<ns0:Date>1999</ns0:Date>
<ns0:ISBN>0-06-566778-9</ns0:ISBN>
<ns0:Publisher>Tibco Software Inc</ns0:Publisher>
</ns0:Book>
</ns0:BookStore>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
预期的 JSON 结果:
"Envelope": {
"Body": {
"BookStore": {
"Book": {
"Title": "The Power of Now",
"Author": "Vivek Ranadive",
"Date": 1999,
"ISBN": "0-06-566778-9",
"Publisher": "Tibco Software Inc"
}
}
}
}
}
Python 代码:
dom = ET.parse('XML_Example01.xml')
xslt = ET.parse('XSLT.xsl')
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(newdom)
我得到的错误:XSLTParseError: xsl:when : could not compile test expression 'normalize-space(.) ne . or not((string(.) castable as xs:integer and not(starts-with(string(.),'+')) and not(starts-with(string(.),'0') and not(. = '0'))) or (string(.) castable as xs:decimal and not(starts-with(string(.),'+')) and not(starts-with(.,'-.')) and not(starts-with(.,'.')) and not(starts-with(.,'-0') and not(starts-with(.,'-0.'))) and not(ends-with(.,'.')) and not(starts-with(.,'0') and not(starts-with(.,'0.'))) )) and not(. = 'false') and not(. = 'true') and not(. = 'null')'
我使用 XSLT 的主要原因是最终添加逻辑来执行强制数组,这样转换后的 JSON 文件具有一致的数组。此外,示例 XML 只是一个通用 XML,实际文件有点复杂且更大,有很多嵌套。
如果我在 XML Spy 中使用相同的 XML 和 XSLT 来执行转换,我不会得到相同的错误。
非常感谢您的帮助
【问题讨论】:
-
lxml仅支持 XSLT 1.0。但是,如果您有 external XSLT 2.0 processor,Python 可以对其进行命令行调用。 -
此外,Saxon/C 提供 XSLT 3.0 并具有 Python 语言绑定。