【问题标题】:How do you modify the xml of a pptx.oxml.xmlchemy.XmlString object at a particular element index?如何在特定元素索引处修改 pptx.oxml.xmlchemy.XmlString 对象的 xml?
【发布时间】:2020-11-04 10:41:56
【问题描述】:

python-pptx 中的 (1x2) 表有一个 tr object 和以下 xml(缩写):

<a:tr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" h="777240">
  <a:tc>
    <a:txBody>
      <a:bodyPr/>
      <a:lstStyle/>
      ...
    </a:txBody>
    <a:tcPr anchor="ctr">
      ...
    </a:tcPr>
  </a:tc>
  <a:tc>
    <a:txBody>
      <a:bodyPr/>
      <a:lstStyle/>
      ...
    </a:txBody>
    <a:tcPr anchor="ctr">
      ...
    </a:tcPr>
  </a:tc>
  <a:extLst>
    <a:ext uri="{0D108BD9-81ED-4DB2-BD59-A6C34878D82A}">
      <a16:rowId xmlns:a16="http://schemas.microsoft.com/office/drawing/2014/main" val="2729466849"/>
    </a:ext>
  </a:extLst>
</a:tr>

运行以下代码(附加新列时):

prs_obj = pptx.Presentation(filepath)
tab = prs_obj.slides[0].shapes[0].table
for tr in tab._tbl.tr_lst:
    new_tc = copy.deepcopy(tr.tc_lst[-1])
    tr.append(new_tc)

在 xml &lt;a:extLst&gt; ...&lt;/a:exLst&gt; 标记之后添加一个新单元格(并使 PowerPoint 无法显示单元格内容)。相反,我想在前两个单元格之后插入另一个 &lt;a:tc&gt; 元素,但在 &lt;a:extLst&gt; 之前。

我阅读的所有关于 xml 的教程都以你有一个可以解析的 xml 文件为前提,即tree = ET.parse(file),但 tr.xml 不是一个可解析的文件,它是一个'pptx.oxml.xmlchemy.XmlString' 对象。

【问题讨论】:

    标签: xml openxml elementtree python-pptx


    【解决方案1】:

    XML 已被解析。您只需要:

    tr.tc_lst[-1].addnext(new_tc)
    

    代替:

    tr.append(new_tc)
    

    这只是lxml._Element 类的其他方法之一,它是所有python-docx 元素的子类。

    【讨论】:

    • 谢谢!这解决了它。我已经投票了(并且也会对其他问题进行投票)。虽然目前我的声望
    • 您可以接受答案(因为您是问题作者),即左侧上/下箭头下方的复选标记符号。此外,您会因接受问题的答案而获得声誉积分。
    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 2017-07-16
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多