python xml.etree.ElementTree append to subelement

前端 未结 2 1806
醉梦人生
醉梦人生 2021-02-02 03:17

I am trying to use xml.etree.ElementTree to parse a xml file, find a specific tag, append a child to that tag, append another child to the newly created tag and add text to the

相关标签:
2条回答
  • 2021-02-02 03:19

    You need to specify b as a parent element for c.

    Also, for getting the a tag you don't need a loop - just take the root (a).

    import xml.etree.ElementTree as ET
    
    tree = ET.parse('test.xml')
    root = tree.getroot()
    
    a = root.find('a')
    b = ET.SubElement(a, 'b')
    c = ET.SubElement(b, 'c')
    c.text = 'text3'
    
    print ET.tostring(root)
    

    prints:

    <root>
        <a>
            <b>
              <c>text1</c>
            </b>
            <b>
              <c>text2</c>
            </b>
            <b>
              <c>text3</c>
            </b>
        </a>
    </root>
    
    0 讨论(0)
  • I prefer to define my own function for adding text:

    def SubElementWithText(parent, tag, text):
        attrib = {}
        element = parent.makeelement(tag, attrib)
        parent.append(element)
        element.text = text
        return element
    

    Which then is very convenient to use as:

    import xml.etree.ElementTree as ET
    
    tree = ET.parse('test.xml')
    root = tree.getroot()
    
    a = root.find('a')
    b = ET.SubElement(a, 'b')
    c = SubElementWithText(b, 'c', 'text3')
    
    0 讨论(0)
提交回复
热议问题