如何使用PowerShell创建新的System.Xml.Linq.XElement [英] How to create a new System.Xml.Linq.XElement with PowerShell

查看:114
本文介绍了如何使用PowerShell创建新的System.Xml.Linq.XElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 System.Xml.Linq 对象以编程方式创建XML DOM.我宁愿解析字符串或从磁盘加载文件以创建DOM.在C#中,这很容易,但是尝试在PowerShell中执行此操作似乎是不可能的.

I want to create an XML DOM programmatically using the System.Xml.Linq objects. I'd rather not parse a string or load a file from disk to create the DOM. In C# this is easy enough, but trying to do this in PowerShell does not seem possible.

选项1 :无效

$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$el = new-Object System.Xml.Linq.XElement "foo"

这会出现以下错误:

new-Object : Cannot convert argument "0", with value: "foo",
 for "XElement" to type "System.Xml.Linq.XElement": "Cannot convert value "foo" to
 type "System.Xml.Linq.XElement". Error: "Data at the root level is invalid. 
 Line 1, position 1.""

选项2:不起作用

$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xname = New-Object System.Xml.Linq.XName "foo"
$el = new-Object System.Xml.Linq.XElement $xname

出现此错误:

New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Xml.Linq.XName.

根据MSDN( http://msdn .microsoft.com/en-us/library/system.xml.linq.xname.aspx )"XName不包含任何公共构造函数.相反,此类提供了String的隐式转换,可让您创建一个XName."

According to MSDN (http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.aspx) "XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an XName."

推荐答案

"XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an XName."

基于此,您可以将String强制转换为XName:

Base on this you can cast String to XName:

$xname = [System.Xml.Linq.XName]"foo"

$xname.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     XName                                    System.Object

然后:

$el = new-Object System.Xml.Linq.XElement $xname
$el


FirstAttribute :
HasAttributes  : False
HasElements    : False
IsEmpty        : True
LastAttribute  :
Name           : foo
NodeType       : Element
Value          :
FirstNode      :
LastNode       :
NextNode       :
PreviousNode   :
BaseUri        :
Document       :
Parent         :
LineNumber     : 0
LinePosition   : 0

这篇关于如何使用PowerShell创建新的System.Xml.Linq.XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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