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

如何动态获取Child节点的所有属性名及其对应值?

动态获取XML中child节点的所有属性名及对应值

问题描述

我有两段XML内容:

第一段:

<Children name='Children'>
  <child name='Child_2' id='2'>child2_Parent_1</child>
  <child name='Child_4' id='4'>child4_Parent_1</child>
  <child name='Child_1' id='3'>child1_Parent_1</child>
  <child name='Child_3' id='1'>child3_Parent_1</child>
</Children>

第二段:

<Children name='Children'>
  <child name='Child_1' id='8'>child1_parent2</child>
  <child name='Child_2' id='7'>child2_parent2</child>
  <child name='Child_4' id='6'>child4_parent2</child>
  <child name='Child_3' id='5'>child3_parent2</child>
</Children>

我需要列出所有<child>节点的属性(比如示例里的name和id),并且通过循环逐个捕获每个属性的名称及其对应值。之前查到的方案都是获取指定名称的属性值,我需要在未知属性名称的情况下,动态获取所有属性名和对应值,求技术解决方案。

解决方案

Python(内置xml.etree.ElementTree)

直接利用节点的attrib属性遍历所有属性,无需提前知道属性名:

import xml.etree.ElementTree as ET

# 解析XML字符串(替换为你的XML内容即可)
xml_content = """
<Children name='Children'>
  <child name='Child_2' id='2'>child2_Parent_1</child>
  <child name='Child_4' id='4'>child4_Parent_1</child>
  <child name='Child_1' id='3'>child1_Parent_1</child>
  <child name='Child_3' id='1'>child3_Parent_1</child>
</Children>
"""
root = ET.fromstring(xml_content)

# 遍历所有child节点
for child_node in root.findall('child'):
    print(f"节点内容: {child_node.text.strip()}")
    # 动态遍历当前节点的所有属性
    for attr_name, attr_value in child_node.attrib.items():
        print(f"属性名: {attr_name}, 属性值: {attr_value}")
    print("---")

Java(DOM解析)

通过NamedNodeMap获取节点的全部属性集合,实现动态遍历:

import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;

public class DynamicXmlAttrReader {
    public static void main(String[] args) throws Exception {
        String xmlContent = """
                <Children name='Children'>
                  <child name='Child_2' id='2'>child2_Parent_1</child>
                  <child name='Child_4' id='4'>child4_Parent_1</child>
                  <child name='Child_1' id='3'>child1_Parent_1</child>
                  <child name='Child_3' id='1'>child3_Parent_1</child>
                </Children>
                """;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(xmlContent.getBytes()));

        NodeList childNodeList = doc.getElementsByTagName("child");
        for (int i = 0; i < childNodeList.getLength(); i++) {
            Node node = childNodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) node;
                System.out.println("节点内容: " + childElement.getTextContent().trim());
                
                // 遍历所有属性
                NamedNodeMap attributes = childElement.getAttributes();
                for (int j = 0; j < attributes.getLength(); j++) {
                    Attr attr = (Attr) attributes.item(j);
                    System.out.println("属性名: " + attr.getName() + ", 属性值: " + attr.getValue());
                }
                System.out.println("---");
            }
        }
    }
}

JavaScript(浏览器/Node.js)

浏览器环境用DOMParser,Node.js可安装xmldom库实现相同逻辑,通过attributes集合动态遍历:

// 浏览器环境示例
const xmlContent = `
<Children name='Children'>
  <child name='Child_2' id='2'>child2_Parent_1</child>
  <child name='Child_4' id='4'>child4_Parent_1</child>
  <child name='Child_1' id='3'>child1_Parent_1</child>
  <child name='Child_3' id='1'>child3_Parent_1</child>
</Children>
`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlContent, "application/xml");
const childNodes = xmlDoc.querySelectorAll("child");

childNodes.forEach(child => {
  console.log(`节点内容: ${child.textContent.trim()}`);
  // 转换为数组后遍历所有属性
  Array.from(child.attributes).forEach(attr => {
    console.log(`属性名: ${attr.name}, 属性值: ${attr.value}`);
  });
  console.log("---");
});

以上方案均无需提前知晓属性名称,直接通过节点的属性集合完成动态遍历,适配任意数量、任意名称的节点属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:49:50