我想使用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 不包含任何公共构造函数。相反,此类提供从 String 的隐式转换允许您创建 XName。”