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

如何使用XPATH表达式优化for循环数量,实现XML节点数据高效提取

实现方案

可以实现仅用单层循环完成需求,核心思路是直接用XPath定位所有AttributeGroupLink节点,遍历节点时直接读取父节点Attribute的ID属性即可,无需先遍历所有Attribute再嵌套遍历其下的分组链接。

示例代码

// 直接查询所有Attribute下的AttributeGroupLink节点
XPathExpression xpGroupLinks = xpath.compile("//STEP-ProductInformation/AttributeList/Attribute/AttributeGroupLink");
NodeList groupLinks = (NodeList) xpGroupLinks.evaluate(doc, XPathConstants.NODESET);

// 单层循环遍历所有分组链接节点
for (int i = 0; i < groupLinks.getLength(); i++) {
    Element groupLink = (Element) groupLinks.item(i);
    // 读取分组ID,直接按属性名获取比按索引取更稳定,避免属性顺序变化导致错误
    String attributeGroupID = groupLink.getAttribute("AttributeGroupID");
    // 获取父节点Attribute的ID
    Element attribute = (Element) groupLink.getParentNode();
    String attributeID = attribute.getAttribute("ID");
    
    // 写入HashMap的逻辑和原来一致
    System.out.println(attributeGroupID);
    if (hashMap.containsKey(attributeGroupID)) {
        hashMap.get(attributeGroupID).add(attributeID);
    } else {
        HashSet<String> newSet = new HashSet<>();
        newSet.add(attributeID);
        hashMap.put(attributeGroupID, newSet);
    }
}

优势说明

  • 省去嵌套循环逻辑,代码更简洁
  • 直接按属性名读取属性值,比原实现中attr.item(0).getNodeValue()的写法更稳定,不会因为节点属性顺序变化出现取值错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:48:00