【问题标题】:Beautifulsoup4, parsing Tableau XML file, and writing to fileBeautifulsoup4,解析 Tableau XML 文件,并写入文件
【发布时间】: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 &amp;apos;[Territory]&amp;apos; then [Territory] End"/>
</column>

问题: 在示例 XML 中,Tableau 期望 XML 被格式化,而 apos; 前面没有 &amp;amp;。它应该只是阅读为&amp;apos;

我尝试过的: 认为我可以转义 & 字符,我在 apos; 之前放置了必要的斜杠以将其转义。部分,但无济于事,我不知道如何形成我的 XML,以便它不会总是将 & 号代码作为我的 XML 中其他特殊字符的一部分。

任何帮助将不胜感激!

【问题讨论】:

    标签: python xml beautifulsoup tableau-api


    【解决方案1】:

    很好的问题描述。

    您的问题被称为“双重转义”。您的程序正在读取已由 XML 处理器序列化的数据。这就是为什么它包含&amp;apos;[{}]&amp;apos; 而不是'[{}]'

    我认为您的程序从文件中读取该 XML 值 作为一个简单的字符串,并将其分配给标签的值。但是当 BeautifulSoup 的 XML 处理器遇到标签值中的 & 时,它必须将其替换为 &amp;amp;。因此,您最终会在 XML 输出中使用 &amp;amp;apos;' 而不是 &amp;apos;

    快速而肮脏的解决方案是编写一些代码将all XML entities 替换为等效文本。更好的解决方案是使用 XML 解析器读取 XML 数据 - 这样,您的程序将自动接收预期的字符串值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2013-09-20
      • 2020-01-09
      • 2015-05-14
      相关资源
      最近更新 更多