PowerShell中无法获取XML根节点Configuration的属性,请求协助
问题
我有一个名为ProjectPro2019Volume_x64.xml的XML文件,内容如下:
<Configuration ID="fe23bffc-bde5-41b4-8862-278c5c1b23ce" Host="cm"> <Add OfficeClientEdition="64" Channel="PerpetualVL2019" OfficeMgmtCOM="TRUE" Version="16.0.10397.20021"> <Product ID="ProPlus2019Volume" PIDKEY="NMMKJ-6RK4F-KMJVX-8D9MJ-6MWKP"> <Language ID="en-us" /> <ExcludeApp ID="Groove" /> <ExcludeApp ID="Lync" /> </Product> <Product ID="ProofingTools"></Product> </Add> <Property Name="SharedComputerLicensing" Value="0" /> <Property Name="FORCEAPPSHUTDOWN" Value="TRUE" /> <Property Name="DeviceBasedLicensing" Value="0" /> <Property Name="SCLCacheOverride" Value="0" /> <Property Name="AUTOACTIVATE" Value="1" /> <RemoveMSI /> <AppSettings> <Setup Name="Company" Value="Big Firm" /> <User Key="software\microsoft\office\16.0\excel\options" Name="defaultformat" Value="51" Type="REG_DWORD" App="excel16" Id="L_SaveExcelfilesas" /> <User Key="software\microsoft\office\16.0\powerpoint\options" Name="defaultformat" Value="27" Type="REG_DWORD" App="ppt16" Id="L_SavePowerPointfilesas" /> <User Key="software\microsoft\office\16.0\word\options" Name="defaultformat" Value="" Type="REG_SZ" App="word16" Id="L_SaveWordfilesas" /> </AppSettings> <Display Level="Full" AcceptEULA="TRUE" /> </Configuration>
执行以下PowerShell命令加载XML文件:
[xml]$xmlFile = Get-Content -Path .\ProjectPro2019Volume_x64.xml
通过$xmlFile.Configuration.Add.Attributes可以正常获取<Add>节点的属性:
PS I:\Sources\Applications\Microsoft\OfficeTest> $xmlFile.Configuration.Add.Attributes #text ----- 64 PerpetualVL2019 TRUE 16.0.10389.20033
但执行$xmlFile.Configuration.Attributes无返回结果,$xmlFile.Configuration.Attributes.Count返回0,无法理解原因,请求帮助。
解答
这是因为PowerShell对XML文档的根节点做了特殊语法处理:它会将根节点的属性直接暴露为节点对象的成员属性,而非通过Attributes集合访问。
正确获取根节点属性的方法:
- 直接访问属性名(最简便):
# 获取ID属性 $xmlFile.Configuration.ID # 获取Host属性 $xmlFile.Configuration.Host
- 使用
GetAttribute()方法:
$xmlFile.Configuration.GetAttribute("ID")
- 通过
PSBase访问底层XmlNode对象的Attributes集合:
如果需要通过Attributes集合查看根节点的所有属性,可以借助PSBase访问原始XML节点对象:
$xmlFile.Configuration.PSBase.Attributes
执行后会返回根节点的所有属性列表:
Name Value ---- ----- ID fe23bffc-bde5-41b4-8862-278c5c1b23ce Host cm
为什么子节点(如<Add>)可以用.Attributes?
对于非根节点的XML元素,PowerShell不会自动将属性映射为对象成员,因此需要通过.Attributes集合访问属性。而根节点作为XML文档的顶级对象,PowerShell做了语法糖处理,简化了属性访问方式。
内容的提问来源于stack exchange,提问作者Papa Smurf
相关产品推荐
相关产品推荐

