我想创建编程方式使用System.Xml.Linq的对象的XML DOM。 我宁愿不解析字符串或从磁盘加载一个文件来创建DOM。 在C#中,这是很容易做到,但尝试这样做在PowerShell中似乎并不可能。
选项1:不工作
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$el = new-Object System.Xml.Linq.XElement "foo"
这提供了以下错误:
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.""
选项2:不工作
$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
它给出了这样的错误:
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Xml.Linq.XName.
根据MSDN( http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.aspx )“的XName不包括任何公共构造函数。但是,此类从字符串提供的隐式转换是允许你创建的XName“。