我有一個結構如下的 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>
每個 Thing 中的屬性并不總是相同的,有些可能存在,有些可能不存在。我像這樣將檔案讀入 $xmldata :
[xml]$xmldata = Get-Content -Path xmlfilename
我像這樣訪問 $xmldata 中的每個“事物”:
$xmldata.XMLFile.Thing
我想使用類似的東西列舉所有的東西屬性
$xmldata.XMLFile.Thing.ForEach({$_.??????})
我用什么代替問號來獲取每個“事物”中所有“東西”專案的串列?
uj5u.com熱心網友回復:
# 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 檔案以避免字符編碼陷阱的可靠方法需要本答案底部部分中描述的技術。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/350143.html
