[英]Removing and replacing specific nodes in an XML file
我一直致力於一個分析樂譜並從中刪除特定音符的項目。 現在我已經從我的代碼中獲得了所需的信息,現在我需要使用我的新信息編輯原始XML分數。 我在Python中這樣做並且已經使用了Minidom所以我顯然希望堅持這一點(我知道這可能是一個愚蠢的選擇,因為這里的很多帖子推薦不同的XML解析方法,因為不太友好的界面目前在Minidom)。
所以在我原來的XML文件中說我有一個由10個音符組成的音樂作品。 注釋的XML格式如下所示:
<note>
<pitch>
<step>E</step>
<alter>-1</alter>
<octave>5</octave>
</pitch>
<duration>72</duration>
</note>
因此,對於每個音符值,這將重復10次。 現在我已經完成了我的分析,我想刪除其中的5個注釋。 刪除我的意思是替換為休息(因為它畢竟是一個樂譜,它有一個符合的形狀)。 因此,XML文件中休息的格式如下所示:
<note>
<rest/>
<duration>72</duration>
</note>
所以我要做的就是刪除音高標簽並用其他標簽替換它。 但是我不確定如何解決這個問題,從我的搜索中找不到任何看似相似的內容。
我並不太關心要刪除要刪除的注釋的位置,因為我已經編寫了一個快速測試工具來展示我將如何在Python中進行下面的操作(xml_format本質上只是包含我的新信息的字典列表)。 它包含與原始XML文件相同數量的注釋,唯一的區別是它們中的一些現在被標記為被刪除。 所以原始文件可能有如下注釋:G,Bb,D,C,G,F,G,D,Bb和xml_format將有G,Bb,D,REMOVE,G,REMOVE,G,D,Bb等。
我剛剛回來了,以確保刪除正確數量的筆記。
def remove_notes(xml_format, filename):
doc = minidom.parse(filename)
count = 0
a = 0
note = doc.getElementsByTagName("note")
for item in note:
if xml_format[count]['step'] == 'Remove':
a = a + 1
# THEN REMOVE THE ENTIRE PITCH TAG, REPLACE WITH REST
count = count + 1
# ELSE DON'T DO ANYTHING
return a
所以基本上我只是在尋找一些語法或代碼的幫助,這些語法或代碼可以用來刪除特定點的特定節點,然后在寫入新文件之前用新節點替換。 非常感謝你的幫助,我希望這是可能的(邏輯似乎並不復雜,但誰知道什么是可能的)!
您需要為每個<note>
節點執行的操作是:
<rest/>
節點 <pitch>
節點 <rest/>
節點替換<pitch>
<rest/>
節點 這是代碼:
def remove_notes(xml_format, filename):
doc = minidom.parse(filename)
count = 0
a = 0
note_nodes = doc.getElementsByTagName("note")
for note_node in note_nodes:
if xml_format[count]['step'] == 'Remove':
a = a + 1
# Create a <rest/> node
rest_node = note_node.ownerDocument.createElement('rest')
# Locate the <pitch> node
pitch_node = note_node.getElementsByTagName('pitch')[0]
# Replace pitch with rest
note_node.replaceChild(rest_node, pitch_node)
count = count + 1
# ELSE DON'T DO ANYTHING
# Finished with the loop, doc now contains the replaced nodes, we need
# to write it to a file
return a
請注意,您需要將更改寫入新文件,否則您的更改將會丟失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.