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

如何用PowerShell从XML中提取aid与对应title的组合信息

解决方法:将aid与对应title组合成两列结果

没问题,你已经完成了最关键的部分,只需要调整一下处理逻辑,把aid和匹配到的title打包成自定义对象,就能得到包含两列的结构化结果了。下面给你两种常用的实现方式:

1. 针对单个指定aid的场景

如果你只需要处理某一个特定aid(比如aid=1)的main类型title,可以这样写:

[xml]$XmlDocument = Get-Content -Path C:\testxml\data.xml
# 先定位到目标anime节点
$targetAnime = $XmlDocument.animetitles.anime | Where-Object {$_.aid -eq 1}
# 筛选对应类型的title,并生成包含aid和title的对象
$targetAnime.title | Where-Object {$_.type -eq 'main'} | ForEach-Object {
    [PSCustomObject]@{
        aid   = $targetAnime.aid
        title = $_.'#text'  # 获取title节点的文本内容
    }
}

执行后会输出类似这样的表格结果:

aid title
--- -----
1   Seikai no Monshou

2. 批量处理所有anime的场景

如果需要遍历所有anime节点,提取每个节点下符合条件的title(比如main类型)并关联对应的aid,可以用这个脚本:

[xml]$XmlDocument = Get-Content -Path C:\testxml\data.xml
# 遍历每个anime节点
$XmlDocument.animetitles.anime | ForEach-Object {
    $currentAid = $_.aid
    # 筛选当前anime下指定类型的title
    $matchingTitles = $_.title | Where-Object {$_.type -eq 'main'}
    # 为每个匹配的title生成一条带aid的记录
    $matchingTitles | ForEach-Object {
        [PSCustomObject]@{
            aid   = $currentAid
            title = $_.'#text'
        }
    }
}

这个脚本会输出所有anime对应的main类型title,格式同样是两列的表格。

小提示

  • 如果需要提取其他类型的title,只需要把Where-Object {$_.type -eq 'main'}中的main替换成你需要的类型(比如official、short、syn)即可。
  • 使用$_.'#text'是因为XML元素的文本内容在PowerShell的XML对象中是存储在#text属性里的,这样能准确获取到标题文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:07:55