如何在Python中向musicXML树添加新元素(elementtree)?

2024-04-28 14:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python批量编辑许多musicXML文件,这些文件当前如下所示:

    <score-partwise>
    ...
      <attributes>
        <transpose>
          <diatonic>-5</diatonic>
          <chromatic>-9</chromatic>
          </transpose>
        </attributes>
    ...
      </score-partwise>

如何在<transpose></transpose>中添加<octave-change>-1</octave-change>,如下所示?在

^{pr2}$

我尝试过:

^{3}$

没有成功。在

非常感谢任何帮助。非常感谢。在


Tags: 文件编辑批量changeattributesscoretransposemusicxml
1条回答
网友
1楼 · 发布于 2024-04-28 14:47:59

只需找到元素并附加:

x = """<score-partwise>    
      <attributes>
        <transpose>
          <diatonic>-5</diatonic>
          <chromatic>-9</chromatic>
          </transpose>
        </attributes>    
      </score-partwise>"""

import xml.etree.ElementTree as et
xml = et.fromstring(x)

#
xml.find("attributes").append(et.fromstring('<transpose><octave-change>-1</octave-change></transpose>'))

print(et.tostring(xml))

这给了你:

^{pr2}$

这还添加了一个新的转置元素,如果您只想附加到现有的转置元素,那么选择它。在

import xml.etree.ElementTree  as et

xml = et.fromstring(x)


xml.find(".//attributes/transpose").append(et.fromstring('<octave-change>-1</octave-change>'))

print(et.tostring(xml))

这给了你:

<score-partwise>
      <attributes>
        <transpose>
          <diatonic>-5</diatonic>
          <chromatic>-9</chromatic>
          <octave-change>-1</octave-change></transpose>
        </attributes>
</score-partwise>

您还可以使用SubElement,它允许您访问节点:

xml = et.fromstring(x)

print(et.tostring(xml))
e = et.SubElement(xml.find(".//attributes/transpose"), "octave-change")
e.text = "-1"
e.tail= "\n"

如果要格式化,您可能会发现lxml是一个更好的选择:

进口lxml.etree作为et

parser = et.XMLParser(remove_blank_text=True)
xml = et.parse("test.xml",parser)


xml.find(".//attributes/transpose").append(et.fromstring('<octave-change>-1</octave-change>'))
xml.write('test.xml', pretty_print=True)

会写下:

<score-partwise>
  <attributes>
    <transpose>
      <diatonic>-5</diatonic>
      <chromatic>-9</chromatic>
      <octave-change>-1</octave-change>
    </transpose>
  </attributes>
</score-partwise>

相关问题 更多 >