Removing and replacing specific nodes in an XML file

I am working on a project that analyzes a musical score and removes specific notes from it. So, now that I have the information needed from my code, now I need to change the original XML account with my new information. I do this in Python and have already used Minidom, so I obviously would like to stick with this (I know that this was probably a stupid choice, as many posts here recommend different XML parsing methods due to the not-so-friendly interface present at Minidom).

So they say in my source XML file, I have a piece of music consisting of only 10 notes. The XML format for the note is shown below:

<note>
  <pitch>
    <step>E</step>
    <alter>-1</alter>
    <octave>5</octave>
  </pitch>
  <duration>72</duration>
</note>

Thus, this will be repeated 10 times for each note value. Now that I have done my analysis, I want to delete 5 of these notes. By removing, I mean replacing the rest (since this is a musical score, and it has a form to fit). Thus, the rest format in the XML file is shown below:

<note>
    <rest/>
    <duration>72</duration>
</note>

So all I have to do is remove the pitch tag and replace it with the rest tag. However, I'm not sure how to do this, in fact, nothing was found from my search, which seems similar.

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

, node , node, . , , , ( , , ).

+3
1

<note> node:

  • <rest/> node
  • <pitch> node
  • <pitch> node <rest/> node

:

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 

, .

0

All Articles