将 XML 转换为 PSObject [英] Convert XML to PSObject

查看:40
本文介绍了将 XML 转换为 PSObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我正在使用 ConvertTo-XML 并且不能使用 Export-Clixml:

Note: I'm using ConvertTo-XML and cannot use Export-Clixml:

我创建了一个简单的PSObject:

I create a simple PSObject:

$a = New-Object PSObject -Property @{
    Name='New'
    Server = $null
    Database = $null
    UserName = $null
    Password = $null
}

然后我使用 ConvertTo-XML 将其转换为 XML:

I then convert it into XML using ConvertTo-XML:

$b = $a | Convertto-XML -NoTypeInformation

XML 如下所示:

<?xml version="1.0"?>
<Objects>
  <Object>
    <Property Name="Password" />
    <Property Name="Name">New</Property>
    <Property Name="Server" />
    <Property Name="UserName" />
    <Property Name="Database" />
  </Object>
</Objects>

我无法找出点符号或 XPath 查询来提取属性/元素并将 $b 转换回原始的 PSObject.

I'm having trouble figuring out the dot notation or XPath query to extract the attributes/elements and convert $b back to the original PSObject.

推荐答案

您可以使用 XPath 轻松完成此操作.尽管 PowerShell 通常使处理 XML 变得非常简单,但在这种情况下,我认为使用严格的 PowerShell 语法的格式会非常粗糙.

You can do this pretty easily with XPath. Although PowerShell usually makes working with XML pretty simple, in this case I think the format using strictly PowerShell syntax would be pretty gross.

filter XmlProperty([String]$Property) {
    $_.SelectSingleNode("/Objects/Object/Property[@Name='$Property']").InnerText
}

$Name = $b | Xmlproperty Name
$Server = $b | XmlProperty Server
# etc...

要对包含一个或多个 Object 元素的 XML 文档一般执行此操作,您可以执行以下操作:

To generically do this for an XML document that contains one or more Object elements, you can do something like this:

function ConvertFrom-Xml($XML) {
    foreach ($Object in @($XML.Objects.Object)) {
        $PSObject = New-Object PSObject
        foreach ($Property in @($Object.Property)) {
            $PSObject | Add-Member NoteProperty $Property.Name $Property.InnerText
        }
        $PSObject
    }
}

ConvertFrom-Xml $b

这篇关于将 XML 转换为 PSObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆