2017-03-02 65 views
0

我們如何使用PowerShell將多個XML文件轉換爲對象?如何將所有XML文件轉換爲XML對象?

假設我們有一個XML文件

$xmlfiles = Get-ChildItem C:\Directory -Filter *.xml 

foreach ($file in $xmlfiles) { 
    [xml]$file Get-Content $_ 
} 

我不知道如何進行一個目錄 - 如果我們要爲它傳遞給查詢每個文件,我們需要嵌套foreach

我只是將XML轉換爲跨多個文檔進行簡單查詢。 我的所有文檔都有相同的模式,我想從每個文檔中選擇一組一致的節點和屬性。

我曾嘗試在評論

foreach ($file in $xmlfiles) { 
    Select-Xml $file -Xpath "//node2" 
} 

建議,但我得到一個運行時異常:

Cannot convert value "sample-document.xml" to type "System.Xml.XmlDocument". Error: 
"The specified node cannot be inserted as the valid child of this node, because the 
specified node is the wrong type." 
At line:1 char:10 
+ foreach ($file in $xmlfiles) { 
+   ~~~~~ 
    + CategoryInfo   : MetadataError: (:) [], ArgumentTransformationMetadataException 
    + FullyQualifiedErrorId : RuntimeException
+0

你能提供一些關於你想要查詢這些文件的信息嗎?你可能不需要將文件內容轉換爲'[xml]'('Select-Xml'可能對你來說更容易) –

+0

哦 - 我不知道 - 我會更新我的問題。 – Sum1sAdmin

回答

4

正如評論所說,你可以使用the Select-Xml cmdlet直接對文件運行XPath查詢。

可以通過管道從Get-ChildItemFileInfo對象直接Select-Xml

Get-ChildItem C:\Directory -Filter *.xml |Select-Xml -XPath '//node2' 

如果您需要使用ForEach-Object或循環做進一步的處理,提供文件的FullName屬性Select-Xml

foreach($xmlFile in Get-ChildItem C:\Directory -Filter *.xml){ 
    $QueryResult = Select-Xml -Path $xmlFile.FullName -XPath '//node2' 
} 
+0

究竟是我之後 - 謝謝@Mathias – Sum1sAdmin

+1

這很酷,我可以用點符號'$ QueryResult.node1.node2'來引用XML,而intellisense將通過節點名稱 – Sum1sAdmin