我正在使用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>'))但没有成功。
任何帮助都是非常感谢的。谢谢。
发布于 2016-04-12 20:36:54
只需找到元素并追加:
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>这还添加了一个新的transpose元素,如果您只想附加到现有的transpose元素,那么选择它。
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>https://stackoverflow.com/questions/36583459
复制相似问题