我有一个 XML 文件,我正在用 Python 解析它并作为 Python 代码输出到文件中。
一些 XML 包含 Reg Ex 值和字符串,它们将在屏幕上显示为对话框,因此我需要维护一些特殊字符。代码如下,但如何做到这一点?
XML 看起来有点像这样;
<variable id="passportnumber" value="" type="String">
<validate>
<regularExpression fieldID="passportnumber" errorID="3007162"><![CDATA[^[a-zA-Z+:?<>;*()%="!0-9./',&\s-]{1,35}$]]></regularExpression>
</validate>
</variable>
对于对话;
<if>
<condition><![CDATA[$taxcode$ == $previousemergencytaxcode$ and $previousemergencytaxcode$ != $emergencytaxcode$]]></condition>
<then>
<dialog id="taxCodeOutdatedDialog" text="Are you sure this is the correct tax
code? The emergency code for the tax year 2011-12 was
'$previousemergencytaxcode$'. The emergency code for the tax
year 2012-13 is '$emergencytaxcode$'. Proceed?" type="YES|NO|CANCEL" />
</then>
</if>
完整的 Python 脚本在这里,解析这两个的细节是;
def parse_regularExpression(self, elem):
self.out('')
self.out("item_regularExpression(fieldID='{0}', value='{1}')".format(elem.attrib['fieldID'],elem.text))
def parse_dialog(self, elem):
self.out('')
self.out("item_dialog(id='{0}', text='{1}', type='{2}')".format(elem.attrib['id'], elem.attrib['text'],elem.attrib['type']))
换行符 (
) 是我不确定如何处理的主要问题。似乎 etree 将其作为换行符输出,即使它是三重引号。它将文本值输出为;
item_dialog(id='taxCodeOutdatedDialog', text='Are you sure this is the correct tax code?
The emergency code for the tax year 2011-12 was '$previousemergencytaxcode$'.
The emergency code for the tax year 2012-13 is '$emergencytaxcode$'.
Proceed?', type='YES|NO|CANCEL')