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

2019-07-25 08:08发布

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

3条回答
地球回转人心会变
2楼-- · 2019-07-25 08:52

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.

查看更多
放我归山
3楼-- · 2019-07-25 09:09

This should work too:

[System.Xml.Linq.XElement]::Parse("<foo/>")
查看更多
狗以群分
4楼-- · 2019-07-25 09:14
"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
查看更多
登录 后发表回答