如何在特定元素索引处修改 pptx.oxml.xmlchemy.XmlString 对象的 xml?

How do you modify the xml of a pptx.oxml.xmlchemy.XmlString object at a particular element index?

python-pptx 中的 (1x2) table 有一个 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 <a:extLst> ...</a:exLst> 标记后添加一个新单元格(并使 PowerPoint 无法显示单元格内容)。相反,我想在前两个单元格之后插入另一个 <a:tc> 元素,但在 <a:extLst>.

之前

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

XML 已经解析。您只需要:

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

而不是:

tr.append(new_tc)

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