You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何循环对比列表数字与XML中field的number属性并输出对应结果

Solution: Match Numbers to XML Field Names

Got it, let's solve this problem step by step. The goal is to cross-reference your number list against the XML's field number attributes and return the corresponding names (or a clear not-found message). Here's a straightforward, runnable example using Python (no external libraries required):

1. Full Code Example

import xml.etree.ElementTree as ET

# Your XML content (can also load directly from a file)
xml_content = """
<fields>
    <field number="2" name="Two" type="STRING"/>
    <field number="6" name="Six" type="STRING"/>
    <field number="7" name="Eight" type="STRING"/>
</fields>
"""

# Your input number list
numbers_to_check = [1, 4, 5, 6]

# Step 1: Parse XML and build a fast lookup mapping
root = ET.fromstring(xml_content)
field_mapping = {}

for field in root.findall('field'):
    # Convert the number attribute to integer to match your list's data type
    field_number = int(field.get('number'))
    field_name = field.get('name')
    field_mapping[field_number] = field_name

# Step 2: Check each number in your list
for num in numbers_to_check:
    if num in field_mapping:
        print(field_mapping[num])
    else:
        print(f"Number {num} does not exist in the XML file.")

2. Breakdown of the Solution

  • XML Parsing: We use Python's built-in xml.etree.ElementTree to read the XML. We loop through every <field> tag and store the number (converted to integer) and corresponding name in a dictionary. This makes lookups quick and efficient.
  • List Checking: For each number in your input list, we check if it exists in our dictionary. If it does, we print the associated name; if not, we print a clear message stating the number isn't present.

3. Loading XML From a File

If your XML is stored in a file instead of a string, replace the ET.fromstring(xml_content) line with this code to load directly from the file:

tree = ET.parse('your_xml_file.xml')
root = tree.getroot()

Sample Output for Your Input

When you run this code with your example list [1,4,5,6], you'll get this output:

Number 1 does not exist in the XML file.
Number 4 does not exist in the XML file.
Number 5 does not exist in the XML file.
Six

This approach is easy to adapt for larger XML files or different input lists—just update the XML content/file path or the number list as needed.

内容的提问来源于stack exchange,提问作者luchad95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:52:51