XmlSerializer 在 PowerShell 中的功能?
有没有办法在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,您可以在 Powershell 中定义类型,并在序列化中使用它。
第一步是定义一个新类型。在 Powershell 2.0 中,您可以通过以下方式执行此操作
调用 Add-Type 。一旦获得包含新类型的动态编译程序集,您就可以像任何其他 .NET 类型一样自由使用该类型。
步骤 2 是像平常一样使用 XmlSerializer 类 - 只需将问题中提供的 C# 代码转换为 Powershell。
下面的例子说明了这一点。它定义一个简单类型,然后从 XML 字符串反序列化以创建该类型的新实例。然后,它打印出该反序列化实例的属性值。
感谢 Keith Hill 指出 Add-Type。
在 Powershell 1.0 中,您可以使用一些自定义代码执行类似的操作(请参阅 Powershell:编译存储在字符串中的 C# 代码) 。
使用该功能,应用程序将变为:
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.
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) .
Using that function, the app becomes: