-->

如何创建PowerShell的新System.Xml.Linq.XElement(How to cr

2019-10-17 17:57发布

我想创建编程方式使用System.Xml.Linq的对象的XML DOM。 我宁愿解析字符串或从磁盘加载一个文件来创建DOM。 在C#中,这是很容易做到,但尝试这样做在PowerShell中似乎并不可能。

选项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不包括任何公共构造函数。但是,此类从字符串提供的隐式转换是允许你创建的XName“。

Answer 1:

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

在此基础上,你可以投StringXName

$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


Answer 2:

这应该工作过:

[System.Xml.Linq.XElement]::Parse("<foo/>")


Answer 3:

有一两件事我注意到你做错了,是[System.Xml.Linq.XElement]有一些自定义的实例,以便落新建 - 对象

$el = [System.Xml.Linq.XElement]::new ([System.Xml.Linq.XName]"foo")

此命名空间中的一切,而不在PowerShell中新建 - 创建的对象。



文章来源: How to create a new System.Xml.Linq.XElement with PowerShell