【问题标题】:Parsing xml with Powershell使用 Powershell 解析 xml
【发布时间】:2020-12-30 15:19:55
【问题描述】:

我不想得到这个xml的所有id(xml不能改变)

<?xml version="1.0" encoding="ISO-8859-1"?>
<List>
 <Person1>
    <Id>E00023</Id>
    <empName>Aadharsh</empName> 
 </Person1>
 <Person2>
    <Id>E00042</Id>
    <empName>Raksha</empName> 
 </Person2>
</List>

我尝试了以下代码,但我不工作:( 问题是 Person1 和 Person2 是不同的名称。 我必须更改什么才能获得所有 ID?

$XMLfile = 'C:\test.xml'
[XML]$empDetails = Get-Content $XMLfile
 
foreach($module in $empDetails.List.$module){
Write-Host "Id :" $module.Id
}

使用这段代码,我只能得到 Person1 的 ID:

$XMLfile = 'C:\test.xml'
[XML]$empDetails = Get-Content $XMLfile
     
foreach($module in $empDetails.List.Person1){
Write-Host "Id :" $module.Id
}

【问题讨论】:

    标签: xml powershell parsing


    【解决方案1】:

    我必须改变什么?

    首先:您需要在 XML 中将 &lt;Person1&gt;&lt;Person2&gt; 更改为 &lt;Person&gt;。不要使用带有反后缀的元素名称,因为这会使处理 XML 变得不必要地困难(并且因为这是完全没有意义的事情 - 如果 XML 中描述了两个人,那么他们都应该是 @ 987654325@)。

    这样做可以使访问 XML 变得容易且合乎逻辑:

    foreach ($person in $empDetails.List.Person) {
        Write-Host "Id :" $person.Id
    }
    

    第二:你需要改变你读取 XML 文件的方式。永远不要使用Get-Content 来读取 XML 文件。始终通过文件路径创建 XML 文档对象和.Load() XML。

    $empDetails = New-Object xml
    $empDetails.Load('C:\test.xml')
    

    这可确保正确处理文件编码(即&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;)。使用Get-Content 不会这样做,这可能会导致数据损坏。

    【讨论】:

    • 感谢您的建议,很遗憾我无法更改 Person1 和 Person2 的名称。我创建这个 xml 只是为了说明我的问题。有没有办法用 Person1 和 Person2 解析 xml?
    • @Thomas 你可以使用$x.List.ChildNodes。 PowerShell 的 XML 接口建立在 .NET 的 System.Xml 对象层次结构之上。你可以做任何那里支持的事情,例如在这种情况下,请使用 System.Xml.XmlElement 必须提供的所有内容 (docs)。
    • 我试过了,但没用...你能帮帮我吗?
    • @Thomas 是的,你的变量不叫$x。不要复制和粘贴我的代码。理解并适应它。
    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 2019-09-27
    • 2021-01-02
    • 2020-12-30
    • 2010-12-15
    • 2020-10-22
    相关资源
    最近更新 更多