转义单引号和lxml

2024-04-18 19:53:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在xml文件中的“代理”节点之后添加一些“兄弟”节点。她就是我写的:

    import os
    from  twb_traduction import parse_twb
    from lxml import etree

    def retrieve_proxy_parent_node(twb_path_source,proxy,key,value):
        tree, root = parse_twb.get_root_tree(twb_path_source)
        nodes = parse_twb.retrieve_node_by_text(root, tree, proxy)
        def parse(tree,root,nodes):
            alias_parent = [parse_twb.get_parent(node, 1) for node in nodes]
            for aliases in alias_parent:
                etree.SubElement(aliases, 'alias', key=key, value=value)
            print(etree.tostring(alias_parent[0]))
            root.write("mon_test.twb", encoding='utf-8', xml_declaration=True, pretty_print=True)
            print('done')
        parse(tree,root,nodes)
        print()

    if __name__ == '__main__':
        ############## Parameters #####################
        # 1-
        input_dir = r'..\..\..\BI\Analyse_Air'
        output_dir = 'data\output\output_demo'
        views_twbsources = [('Analyse Air', 'QAL_Analyse Air - Copie.twb')]
        for view, twb_name_source in views_twbsources:
            input_filepath =  os.path.join(input_dir, twb_name_source)
            key = r"'Allemagne'"
            retrieve_proxy_parent_node(input_filepath,proxy="Alias_Dep",key=r"'Allemagne'",value="Alias_Dep_Allemagne")

结果如下:

<aliases xmlns:user="http://www.tableausoftware.com/xml/user">
    <alias key="&quot;Albanie&quot;" value="Alias_Dep_Albanie"/>
    <alias key="&quot;Alg&#233;rie&quot;" value="Alias_Dep_Alg&#233;rie"/>
    <alias key="\'Allemagne\'" value="Alias_Dep_Allemagne"/>
    <alias key="\'Allemagne\'" value="Alias_Dep_Allemagne"/>
</aliases>

如您所见,打印显示的是key="\'Allemagne\'",而不是key="&quote;Allemagne&quote;"

我尝试了其他组合,但没有任何效果,正如您所看到的:

# 1
retrieve_proxy_parent_node(input_filepath,proxy="Alias_Dep",key=r"&quot;Allemagne&quot;",value="Alias_Dep_Allemagne") # give for Allemagne: <alias key="&amp;quot;Allemagne&amp;quot;" value="Alias_Dep_Allemagne"/></aliases>
# 2
retrieve_proxy_parent_node(input_filepath,proxy="Alias_Dep",key=r"&quot;Allemagne&quot;",value="Alias_Dep_Allemagne")  # give for Allemagne: <alias key="&amp;quot;Allemagne&amp;quot;" value="Alias_Dep_Allemagne"/></aliases>\n 

Tags: keynodeinputparsevaluealiasrootparent