2013-02-22 40 views
1

我想創建編程方式使用System.Xml.Linq的對象的XML DOM。我寧願不是解析字符串或從磁盤加載文件來創建DOM。在C#中這很簡單,但在PowerShell中嘗試這樣做似乎不可行。如何創建一個新的System.Xml.Linq.XElement使用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「這個

回答

7
"XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an XName." 

基地,你可以投StringXName

$xname = [System.Xml.Linq.XName]"foo" 

$xname.GetType() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  XName         System.Object 

則:

$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 
5

這也應該工作:

[System.Xml.Linq.XElement]::Parse("<foo/>") 
+0

確認。這也適用。 – saveenr 2014-10-26 08:43:41

0

一兩件事我注意到你做錯了,是[System.Xml.Linq.XElement]有一些自定義的實例,以便落新建 - 對象在這個命名空間

$el = [System.Xml.Linq.XElement]::new ([System.Xml.Linq.XName]"foo") 

一切,而不需要在PowerShell中新建 - 對象被創建。