Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new System.Xml.Linq.XElement with 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.

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

like image 282
saveenr Avatar asked Oct 19 '25 02:10

saveenr


2 Answers

"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
like image 108
CB. Avatar answered Oct 22 '25 05:10

CB.


This should work too:

[System.Xml.Linq.XElement]::Parse("<foo/>")
like image 29
Craig - MSFT Avatar answered Oct 22 '25 04:10

Craig - MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!