xml - 如何使用 Powershell 枚举 XML 元素的属性

标签 xml powershell enumerate

我有一个结构如下的 XML 文件:

<XMLFile>
    <Thing Stuff1='data' Stuff2='data' Stuff3='data' .....Stuff100='data'</Thing>
    <Thing Stuff1='data' Stuff2='data' Stuff3='data' .....Stuff85='data'</Thing>
    <Thing Stuff1='data' Stuff2='data' Stuff3='data' .....Stuff91='data'</Thing>
    .
    .
    .
</XMLFile>

每个事物的属性并不总是相同,有些可能存在,有些可能不存在。我将文件读入 $xmldata,如下所示:

[xml]$xmldata = Get-Content -Path xmlfilename

我像这样访问 $xmldata 中的每个“事物”:

$xmldata.XMLFile.Thing

我想使用类似的方法枚举所有的 Stuff 属性

$xmldata.XMLFile.Thing.ForEach({$_.??????})

我应该使用什么来代替问号来获取每个“事物”中所有“东西”项目的列表?

最佳答案

# Parse the XML file into a DOM.
[xml] $xmldata = Get-Content -Raw -LiteralPath xmlfilename

# Loop over the 'Thing' elements' attributes and emit them as 
# custom objects with names and values.
$xmlData.XMLFile.Thing.Attributes.ForEach({ 
  [pscustomobject] @{ Name = $_.Name; Value = $_.Value }
})

请注意使用 -Raw 来加快将输入文件解析为 XML DOM 的速度。然而,解析 XML 文件并避免字符编码陷阱的稳健方法需要 this answer 底部部分中描述的技术。 .

关于xml - 如何使用 Powershell 枚举 XML 元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69859783/

相关文章:

Swift - enumerateChildNodesWithName 名称包含字符串

python 在for循环中删除一个元素

c# - Powershell 中的 DataTable.Rows.Find(MultiplePrimaryKey)

powershell - Linux PowerShell 中的 'nohup' 是什么?

Objective-C:逐行读取文件

html - 基于多个子级的 XPath 父级

java - 没有字段的派生类的 Hibernate 映射

python - odoo 8 中 bool 字段的 onchange 函数

ruby - Nokogiri SAX 忽略空字符

c# - 在 C# 中替代 ">"on String 就像在 Powershell 中一样?