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

Angular/JavaScript:如何匹配for循环输出中的'author'文本

问题描述

通过for循环从XML中提取所有标签名后,需要在控制台循环输出的标签名中匹配author,匹配成功时执行对应的条件判断逻辑。

现有代码

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: "./app.component.html",
  styleUrls: "./app.component.css"
})
export class AppComponent implements OnInit {
  title = 'project';

  ngOnInit(): void {
    let xmldata = "<bookstore><book>" +
      "<title>Everyday Italian</title>" +
      "<author>Giada De Laurentiis</author>" +
      "<year>2005</year>" +
      "</book></bookstore>";
    var node = (new DOMParser()).parseFromString(xmldata, "text/xml").documentElement;
    var nodes = node.querySelectorAll("*");
    // console.log(nodes[4].tagName)
    for (var i = 0; i < nodes.length; i++) {
      var text = null;
      if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == 3) //if nodeType == text node
        text = nodes[i].textContent; //get text of the node
      //  console.log("TageName : ", nodes[i].tagName, ", Text : ", text);
      console.log(nodes[i].tagName)
    }
  }
}
解决方案

在循环内部添加标签名匹配判断,当标签名等于author时执行自定义逻辑。示例中以打印标签内容为例,你可以替换为自己的业务逻辑:

修改后的代码如下:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: "./app.component.html",
  styleUrls: "./app.component.css"
})
export class AppComponent implements OnInit {
  title = 'project';

  ngOnInit(): void {
    let xmldata = "<bookstore><book>" +
      "<title>Everyday Italian</title>" +
      "<author>Giada De Laurentiis</author>" +
      "<year>2005</year>" +
      "</book></bookstore>";
    var node = (new DOMParser()).parseFromString(xmldata, "text/xml").documentElement;
    var nodes = node.querySelectorAll("*");
    for (var i = 0; i < nodes.length; i++) {
      var text = null;
      if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == 3)
        text = nodes[i].textContent;
      
      const tagName = nodes[i].tagName;
      console.log(tagName);
      
      // 匹配author标签,执行条件逻辑
      if (tagName === 'author') {
        console.log("找到author标签,内容为:", text);
        // 此处可添加其他需执行的业务逻辑
      }
    }
  }
}

关键说明

  • 先将当前循环的标签名存入tagName变量,便于后续判断和复用
  • 使用===进行严格匹配(XML标签名大小写敏感,确保匹配时大小写一致)
  • 匹配成功后,可直接使用之前获取的text变量,或是添加自定义业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:54:59