4

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

saveenr
  • 8,439
  • 3
  • 19
  • 20

3 Answers3

9
"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
CB.
  • 58,865
  • 9
  • 159
  • 159
5

This should work too:

[System.Xml.Linq.XElement]::Parse("<foo/>")
Craig - MSFT
  • 596
  • 9
  • 13
0

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.

Alexan
  • 8,165
  • 14
  • 74
  • 101
David Morrow
  • 262
  • 4
  • 9