【发布时间】:2021-12-07 14:55:45
【问题描述】:
我遇到了一个问题,我使用 beautifulsoup 解析从 Tableau 工作簿生成的 xml,当我将结果写入文件时,它的行为与预期不符。选择 bs4,它是标准的 XML 解析器,因为我发现它最容易让我的大脑理解,而且我不需要 lxml 解析器/包的速度。
背景:我的 Tableau 工作簿中有一个计算字段,它将在发布期间以编程方式更改,具体取决于模板工作簿将转到的服务器和站点位置。我已经完成并构建了一些函数并编写了获取数据所需的所有内容,但是当我的脚本将 xml 写入文件时,它会为 & 符号添加一些编码。这会导致文件有效并且能够在 Tableau 中打开,但该字段被视为无效,尽管它看起来是有效的。我认为 XML 在我的流程中的某个地方会出现格式错误。
到目前为止我认为问题所在的代码:
import bs4 as bs
twb = open(Script_config['local_file_location'], 'r')
bs_content = bs(twb, 'xml')
# formula_final below comes from another script that handles getting the data I need to programmatically generate the formula I need.
# Here is what I use to generate the bulk of the formula for Tableau
# 'When '[{}]' then {} '.format(rows['Column_Name'], rows['Formatted_ColumnName']))
# Does some other stuff and slaps together the formula I need as a string that can be written into my XML
# Verified that my result is coming over correctly and only changes once I do the replacement here and/or the writing of the file.
for calculation in bs_content.find_all('column', {'caption': 'Group By', 'datatype':'string', 'name':'[Calculation_12345678910]'}):
calculation.find('calculation')['formula'] = formula_final
with open('test.twb', 'w') as file:
file.write(str(bs_content))
示例 XML:
<?xml version="1.0" encoding="utf-8"?>
<workbook source-build="2021.1.4 (20211.21.0712.0907)" source-platform="win" version="18.1" xml:base="https://localhost" xmlns:user="http://www.tableausoftware.com/xml/user">
...
<column caption="Group By" datatype="string" name="[Calculation_12345678910]" role="dimension" type="nominal">
<calculation class="tableau" formula="Case [Parameters].[Location External ID Parameter] When &apos;[Territory]&apos; then [Territory] End"/>
</column>
问题:
在示例 XML 中,Tableau 期望 XML 被格式化,而 apos; 前面没有 &amp;。它应该只是阅读为&apos;。
我尝试过的: 认为我可以转义 & 字符,我在 apos; 之前放置了必要的斜杠以将其转义。部分,但无济于事,我不知道如何形成我的 XML,以便它不会总是将 & 号代码作为我的 XML 中其他特殊字符的一部分。
任何帮助将不胜感激!
【问题讨论】:
标签: python xml beautifulsoup tableau-api