【问题标题】:How to use Powershell to enumerate attributes of an XML element如何使用 Powershell 枚举 XML 元素的属性
【发布时间】:2021-12-19 21:28:21
【问题描述】:

我有一个结构如下的 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({$_.??????})

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

【问题讨论】:

    标签: xml powershell enumerate


    【解决方案1】:
    # 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 底部部分中描述的技术。

    【讨论】:

    • 我知道属性必须在某个地方,我只是将它放入 ForEach 中。漂亮,也感谢 -RAW 信息。谢谢!!!
    • 很高兴听到它有帮助,@dstroupe;我的荣幸。
    • 什么是 DOM。?
    • @AbrahamZinala,是Document Object Model的缩写
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多