python - 转义单引号和 lxml
问题描述
我想在 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=""Albanie"" value="Alias_Dep_Albanie"/>
<alias key=""Algérie"" value="Alias_Dep_Algérie"/>
<alias key="\'Allemagne\'" value="Alias_Dep_Allemagne"/>
<alias key="\'Allemagne\'" value="Alias_Dep_Allemagne"/>
</aliases>
如您所见,打印显示key="\'Allemagne\'"
而不是key=""e;Allemagne"e;"
我尝试了其他组合,但没有任何效果,如您所见:
# 1
retrieve_proxy_parent_node(input_filepath,proxy="Alias_Dep",key=r""Allemagne"",value="Alias_Dep_Allemagne") # give for Allemagne: <alias key="&quot;Allemagne&quot;" value="Alias_Dep_Allemagne"/></aliases>
# 2
retrieve_proxy_parent_node(input_filepath,proxy="Alias_Dep",key=r""Allemagne"",value="Alias_Dep_Allemagne") # give for Allemagne: <alias key="&quot;Allemagne&quot;" value="Alias_Dep_Allemagne"/></aliases>\n
解决方案
推荐阅读
- angular - Angular 6:设置滚动条以在有效负载中添加用户数据
- sql - 如何在没有源数据库的情况下执行 INSERT 查询时避免重复的 SQL 数据
- relational-algebra - 关系代数找到第一个值
- ios - iOS Fastlane Match 代码签名问题
- excel - 下载嵌入式 PDF 文件
- javascript - 为什么我的滑块中的某些幻灯片不移动?
- android - AdMobs 测试广告在 Galaxy NOTE 8 上不可见
- css - 使用 css 用连续点(。)自动换行
- javascript - 可以 (x++ !== x) && (x++ === x); 返回真?
- javascript - 仅在搜索模式下显示结果