简体   繁体   中英

How can I use etree to iterate and replace xml table content if new version provided as input

Basically, I need to iterate over all environments (ie AUX, INT, UAT, etc.) and replace the version number with a new one that I specify as input.

I'd like to do it without writing a file. Instead, my xml is captured as a variable named page_content

here's my xml:

<body>
<p class="auto-cursor-target"><br /></p>
<table class="wrapped">
    <colgroup>
        <col />
        <col />
    </colgroup>
    <tbody>
        <tr>
            <th>Environment</th>
            <th>Version</th>
        </tr>
        <tr>
            <td>INT</td>
            <td>1.2.3-5</td>
        </tr>
        <tr>
            <td>XQA</td>
            <td><br /></td>
        </tr>
        <tr>
            <td colspan="1">UAT</td>
            <td colspan="1"><br /></td>
        </tr>
        <tr>
            <td colspan="1">AUX</td>
            <td colspan="1"><br /></td>
        </tr>
        <tr>
            <td colspan="1">SIT</td>
            <td colspan="1"><br /></td>
        </tr>
        <tr>
            <td colspan="1">PQA</td>
            <td colspan="1"><br /></td>
        </tr>
        <tr>
            <td colspan="1">Production</td>
            <td colspan="1"><br /></td>
        </tr>
    </tbody>
</table>
<p class="auto-cursor-target"><br /></p>
</body>

You can use xpath to find the tag and then update the value

Below function updates the version in given xml string and returns updated xml string

def fun(xml_data, env, version):
    root = ET.fromstring(xml_data)
    node = root.find(f".//tr[td='{env}']/td[2]")
    if node:
        node.text = version
    return ET.tostring(root).decode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM