1

我有一个 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? &#10; &#10;The emergency code for the tax year 2011-12 was
        '$previousemergencytaxcode$'. &#10;The emergency code for the tax
        year 2012-13 is '$emergencytaxcode$'. &#10; &#10;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']))

换行符 ( &#10;) 是我不确定如何处理的主要问题。似乎 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')
4

1 回答 1

1

我认为这正是你告诉它做的事情。XML 包含&#10我认为的换行符。然后你打印出那个字符串。

如果您想用打印输出中的其他内容替换换行符,那么您最好在阅读后但在输出之前这样做。(而不是试图在 XML 中更改它)。

您的代码最终将如下所示:

def parse_dialog(self, elem):
    self.out('')
    self.out("item_dialog(id='{0}', text='{1}', type='{2}')".format(
       escape_string(elem.attrib['id']),
       escape_string(elem.attrib['text']),
       escape_string( elem.attrib['type']) ))

def escape_string(s):
  ... 

这也更加强大,因为您的问题本质上是脚本注入问题/漏洞。

于 2012-05-08T08:58:15.813 回答