XmlSerializer 在 PowerShell 中的功能?

发布于 2024-08-31 10:00:36 字数 489 浏览 8 评论 0原文

有没有办法在 PowerShell 中利用 .NET 的 XmlSerializer 类的功能?

更具体地说,能够轻松地将 .NET 类型反/序列化为 Xml,例如

XmlSerializer s = new XmlSerializer(typeof(MyType));
TextReader r = new StreamReader("sample.xml");
MyType myType = (MyType)s.Deserialize(r);
r.Close();

我知道我可以从 PowerShell 调用上面的内容,但是有没有办法避免在单独的程序集中定义 MyType?谢谢

[编辑] 由于似乎无法从 PowerShell 添加类似 .NET 的类型,请允许我重新定位我的问题:是否有一种简单的方法(如 XmlSerializer)可以在 PowerShell 中序列化类型?我必须从 PS 读取/写入一些 .xml,并且宁愿在手动执行之前利用此类功能。

Is there a way to leverage the functionality of .NET's XmlSerializer class in PowerShell?

More specifically, the ability to easily de/serialize .NET types into Xml e.g.

XmlSerializer s = new XmlSerializer(typeof(MyType));
TextReader r = new StreamReader("sample.xml");
MyType myType = (MyType)s.Deserialize(r);
r.Close();

I know I can call above from PowerShell, but is there a way to avoid defining MyType in a separate assembly? Thanks

[Edit] Since seems to be that .NET-like types cannot be added from PowerShell, allow me to re-target my question: is there an easy way, like XmlSerializer, to serialize types in PowerShell? I have to read/write some .xml's from PS, and would rather leverage such functionality before manually doing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

—━☆沉默づ 2024-09-07 10:00:36

当然,您可以在 Powershell 中定义类型,并在序列化中使用它。

第一步是定义一个新类型。在 Powershell 2.0 中,您可以通过以下方式执行此操作
调用 Add-Type 。一旦获得包含新类型的动态编译程序集,您就可以像任何其他 .NET 类型一样自由使用该类型。

步骤 2 是像平常一样使用 XmlSerializer 类 - 只需将问题中提供的 C# 代码转换为 Powershell。

下面的例子说明了这一点。它定义一个简单类型,然后从 XML 字符串反序列化以创建该类型的新实例。然后,它打印出该反序列化实例的属性值。

$source1 = @"
using System;
using System.Xml;
using System.Xml.Serialization;

namespace MyDynamicTypes
{
    [XmlRoot]
    public class Foo
    {
    [XmlElement]
    public string Message { get; set; }

    [XmlAttribute]
    public int Flavor { get; set; }
    }
}
"@

Add-Type -TypeDefinition $source1 -Language "CSharpVersion3" -ReferencedAssemblies System.Xml.dll

$xml1 = @"
<Foo Flavor='19'>
  <Message>Ephesians 5:11</Message>
</Foo>
"@

$f1 = New-Object MyDynamicTypes.Foo
$sr = New-Object System.IO.StringReader($xml1)
$s1 = New-Object System.Xml.Serialization.XmlSerializer( $f1.GetType() )
$xtr = New-Object System.Xml.XmlTextReader($sr)
$foo = $s1.Deserialize($xtr)

Write-Output ("foo.Flavor = " + $foo.Flavor)
Write-Output ("foo.Message = " + $foo.Message)

感谢 Keith Hill 指出 Add-Type。


在 Powershell 1.0 中,您可以使用一些自定义代码执行类似的操作(请参阅 Powershell:编译存储在字符串中的 C# 代码) 。

function Compile-Code {
param (
    [string[]] $code       = $(throw "The parameter -code is required.")
  , [string[]] $references = @()
  , [switch]   $asString   = $false
  , [switch]   $showOutput = $false
  , [switch]   $csharp     = $true
  , [switch]   $vb         = $false
)

$options    = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]";
$options.Add( "CompilerVersion", "v3.5")

if ( $vb ) {
    $provider = New-Object Microsoft.VisualBasic.VBCodeProvider $options
} else {
    $provider = New-Object Microsoft.CSharp.CSharpCodeProvider $options
}

$parameters = New-Object System.CodeDom.Compiler.CompilerParameters

@( "mscorlib.dll", "System.dll", "System.Core.dll", "System.Xml.dll", ([System.Reflection.Assembly]::GetAssembly( [PSObject] ).Location) ) + $references | Sort -unique |% { $parameters.ReferencedAssemblies.Add( $_ ) } | Out-Null

$parameters.GenerateExecutable = $false
$parameters.GenerateInMemory   = !$asString
$parameters.CompilerOptions    = "/optimize"

if ( $asString ) {
    $parameters.OutputAssembly = [System.IO.Path]::GetTempFileName()
}

$results = $provider.CompileAssemblyFromSource( $parameters, $code )

if ( $results.Errors.Count -gt 0 ) {
    if ( $output ) {
    $results.Output |% { Write-Output $_ }
    } else {
    $results.Errors |% { Write-Error $_.ToString() }
    }
} else {
    if ( $asString ) {
    $content = [System.IO.File]::ReadAllBytes( $parameters.OutputAssembly )
    $content = [Convert]::ToBase64String( $content )

    [System.IO.File]::Delete( $parameters.OutputAssembly );

    return $content
    } else {
    return $results.CompiledAssembly
    }
}
}

使用该功能,应用程序将变为:

$source1 = @"
using System;
using System.Xml;
using System.Xml.Serialization;

namespace MyDynamicTypes
{
    [XmlRoot]
    public class Foo
    {
    [XmlElement]
    public string Message { get; set; }

    [XmlAttribute]
    public int Flavor { get; set; }
    }
}
"@

Compile-Code -csharp -code $source1

$xml1 = @"
<Foo Flavor='19'>
  <Message>Ephesians 5:11</Message>
</Foo>
"@

$f1 = New-Object MyDynamicTypes.Foo
$sr = New-Object System.IO.StringReader($xml1)
$s1 = New-Object System.Xml.Serialization.XmlSerializer( $f1.GetType() )
$xtr = New-Object System.Xml.XmlTextReader($sr)
$foo = $s1.Deserialize($xtr)

Write-Output ("foo.Flavor = " + $foo.Flavor)
Write-Output ("foo.Message = " + $foo.Message)

Sure, you can define a type within Powershell, and use it in serialization.

The first step is defining a new type. In Powershell 2.0, you can do that by
calling Add-Type . Once you have the dynamically-compiled assembly containing the new type, you can use the type freely, as any other .NET type.

Step 2 is to just use the XmlSerializer class, as you would normally - just translate the C# code you provided in the question to Powershell.

The following example illustrates. It defines a simple type, then deserializes from an XML string to create a new instance of that type. It then prints out the property values on that de-serialized instance.

$source1 = @"
using System;
using System.Xml;
using System.Xml.Serialization;

namespace MyDynamicTypes
{
    [XmlRoot]
    public class Foo
    {
    [XmlElement]
    public string Message { get; set; }

    [XmlAttribute]
    public int Flavor { get; set; }
    }
}
"@

Add-Type -TypeDefinition $source1 -Language "CSharpVersion3" -ReferencedAssemblies System.Xml.dll

$xml1 = @"
<Foo Flavor='19'>
  <Message>Ephesians 5:11</Message>
</Foo>
"@

$f1 = New-Object MyDynamicTypes.Foo
$sr = New-Object System.IO.StringReader($xml1)
$s1 = New-Object System.Xml.Serialization.XmlSerializer( $f1.GetType() )
$xtr = New-Object System.Xml.XmlTextReader($sr)
$foo = $s1.Deserialize($xtr)

Write-Output ("foo.Flavor = " + $foo.Flavor)
Write-Output ("foo.Message = " + $foo.Message)

Thanks to Keith Hill for pointing Add-Type out.


In Powershell 1.0, you can do something similar with some custom code (see Powershell: compiling c# code stored in a string) .

function Compile-Code {
param (
    [string[]] $code       = $(throw "The parameter -code is required.")
  , [string[]] $references = @()
  , [switch]   $asString   = $false
  , [switch]   $showOutput = $false
  , [switch]   $csharp     = $true
  , [switch]   $vb         = $false
)

$options    = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]";
$options.Add( "CompilerVersion", "v3.5")

if ( $vb ) {
    $provider = New-Object Microsoft.VisualBasic.VBCodeProvider $options
} else {
    $provider = New-Object Microsoft.CSharp.CSharpCodeProvider $options
}

$parameters = New-Object System.CodeDom.Compiler.CompilerParameters

@( "mscorlib.dll", "System.dll", "System.Core.dll", "System.Xml.dll", ([System.Reflection.Assembly]::GetAssembly( [PSObject] ).Location) ) + $references | Sort -unique |% { $parameters.ReferencedAssemblies.Add( $_ ) } | Out-Null

$parameters.GenerateExecutable = $false
$parameters.GenerateInMemory   = !$asString
$parameters.CompilerOptions    = "/optimize"

if ( $asString ) {
    $parameters.OutputAssembly = [System.IO.Path]::GetTempFileName()
}

$results = $provider.CompileAssemblyFromSource( $parameters, $code )

if ( $results.Errors.Count -gt 0 ) {
    if ( $output ) {
    $results.Output |% { Write-Output $_ }
    } else {
    $results.Errors |% { Write-Error $_.ToString() }
    }
} else {
    if ( $asString ) {
    $content = [System.IO.File]::ReadAllBytes( $parameters.OutputAssembly )
    $content = [Convert]::ToBase64String( $content )

    [System.IO.File]::Delete( $parameters.OutputAssembly );

    return $content
    } else {
    return $results.CompiledAssembly
    }
}
}

Using that function, the app becomes:

$source1 = @"
using System;
using System.Xml;
using System.Xml.Serialization;

namespace MyDynamicTypes
{
    [XmlRoot]
    public class Foo
    {
    [XmlElement]
    public string Message { get; set; }

    [XmlAttribute]
    public int Flavor { get; set; }
    }
}
"@

Compile-Code -csharp -code $source1

$xml1 = @"
<Foo Flavor='19'>
  <Message>Ephesians 5:11</Message>
</Foo>
"@

$f1 = New-Object MyDynamicTypes.Foo
$sr = New-Object System.IO.StringReader($xml1)
$s1 = New-Object System.Xml.Serialization.XmlSerializer( $f1.GetType() )
$xtr = New-Object System.Xml.XmlTextReader($sr)
$foo = $s1.Deserialize($xtr)

Write-Output ("foo.Flavor = " + $foo.Flavor)
Write-Output ("foo.Message = " + $foo.Message)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文