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

时间:2016-04-12 20:29:21

标签: python xml elementtree musicxml

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

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

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

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

我试过这个:

import xml.etree.ElementTree as ET

attributes   = ET.Element("attributes")
attributes.append(ET.fromstring('<transpose><octave-change>-1</octave-change></transpose>'))

没有成功。

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

1 个答案:

答案 0 :(得分:2)

找到元素并追加:

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))

这给了你:

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

如果您只想附加到现有的转置元素,那么也会添加一个新的转置元素,然后选择它。

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导入为

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>