【问题标题】:Maintaining special characters when parsing XML with Python?使用 Python 解析 XML 时维护特殊字符?
【发布时间】:2012-05-08 08:46:34
【问题描述】:

我有一个 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 脚本是 here,解析这两个脚本的细节是;

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']))

换行符 (&amp;#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')

【问题讨论】:

    标签: python xml xml-parsing special-characters


    【解决方案1】:

    我认为这正是您要它做的事情。 XML 包含&amp;#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):
      ... 
    

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

    【讨论】:

    • 是的!有时候,当我考虑太多时,我只需要有人指出显而易见的事情!谢谢。现在只需要找出一个正则表达式来子值:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2012-09-30
    相关资源
    最近更新 更多