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."
One thing I noticed your doing wrong is [System.Xml.Linq.XElement] has some custom instance so drop New- Object
Everything in this namespace is created without New- Object in powershell.
This should work too:
Base on this you can cast
String
toXName
:then: