How to create a new System.Xml.Linq.XElement with PowerShell

守給你的承諾、 提交于 2019-12-24 13:26:16

问题


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.

Option 1: Doesn't work

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

This gives the following error:

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.""

Option 2: Doesn't work

$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

It gives this error:

New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Xml.Linq.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."


回答1:


"XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an 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

then:

$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



回答2:


This should work too:

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



回答3:


One thing I noticed your doing wrong is [System.Xml.Linq.XElement] has some custom instance so drop New- Object

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

Everything in this namespace is created without New- Object in powershell.



来源:https://stackoverflow.com/questions/15016037/how-to-create-a-new-system-xml-linq-xelement-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!