Skip to main content
 首页 » 编程设计

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

2024年10月24日8Free-Thinker

我正在使用 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>')) 

没有成功。

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

请您参考如下方法:

只需找到元素并追加:

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