如何在xmlfi中使用python插入值

2024-04-25 13:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,刚刚开始学习python 以下是我的xml文件:

    <Build_details>
      <Release number="1902">
        <Build number="260">
          <OMS>
            <Build_path>ST_OMS_V1810_B340</Build_path>
            <Pc_version>8041.30.01</Pc_version>
          </OMS>
          <OMNI>
            <Build_path>ST_OMNI_V1810_B340</Build_path>
          </OMNI>
        </Build>
      </Release>
      <Release number="1810">
        <Build number="230">
          <OMS>
            <Build_path>ST_OMS_909908</Build_path>
            <Pc_version>8031.25.65</Pc_version>
          </OMS>
          <OMNI>
            <Build_path>ST_OMNI_798798789789</Build_path>
          </OMNI>
        </Build>
      </Release>
      <Release number="1806">
        <Build number="300">
          <OMS>
            <Build_path>ST_OMS_V18102_B300</Build_path>
            <Pc_version>8041.30.01</Pc_version>
          </OMS>
          <OMNI>
            <Build_path>ST_OMNI_V18102_B300</Build_path>
          </OMNI>
        </Build>
      </Release>
    </Build_details>

How can i insert below chunk of data by asking release no to user and insert below it :
    <Build number="230">
      <OMS>
        <Build_path>ST_OMS_909908</Build_path>
        <Pc_version>8031.25.65</Pc_version>
      </OMS>
      <OMNI>
        <Build_path>ST_OMNI_798798789789</Build_path>
      </OMNI>
    </Build>

我需要搜索特定版本,然后添加详细信息到它。拜托帮助 我不是不能遍历xml来找到特定的版本


Tags: pathbuildnumberreleaseversionxmldetailsoms
2条回答

下面是使用python内置库xml的解决方案, 您必须首先找到release元素,然后创建一个新的构建元素并附加到release元素中。在

import xml.etree.ElementTree as ET if __name__ == "__main__": release_number = input("Enter the release number\n").strip() tree = ET.ElementTree(file="Build.xml") # Original XML File root = tree.getroot() for elem in root.iterfind('.//Release'): # Find the release element if elem.attrib['number'] == release_number: # Create new Build Element build_elem = ET.Element("Build", {"number": "123"}) # OMS element oms_elem = ET.Element("OMS") build_path_elem = ET.Element("Build_path") build_path_elem.text = "ST_OMS_909908" pc_version_elem = ET.Element("Pc_version") pc_version_elem.text = "8031.25.65" oms_elem.append(build_path_elem) oms_elem.append(pc_version_elem) omni_elem = ET.Element("OMNI") build_path_omni_elem = ET.Element("Build_path") build_path_omni_elem.text = "ST_OMNI_798798789789" omni_elem.append(build_path_omni_elem) build_elem.append(oms_elem) build_elem.append(omni_elem) elem.append(build_elem) # Write to file tree.write("Build_new.xml") # After adding the new element

和13;
和13;

我不能添加我的评论,因为声誉不好。在

通过这个链接Reading XML file and fetching its attributes value in Python

相关问题 更多 >