循环遍历XML文件powershell

时间:2013-10-16 16:00:43

标签: xml loops powershell

我正在尝试从XML文件中提取一些内容。我有我需要为一个文件工作,但我需要为目录中的所有文件。到目前为止我所拥有的是:

$files = Get-ChildItem C:\Users\rasuser\Desktop\import *.xml -recurse

foreach ($file in $files){

$MyXml = [xml](Get-Content $file)

#$path = $file.ExportedContentItem.path
#$name = $file.ExportedContentItem.name
#$GUID = $file.ExportedContentItem.ID

#$path + "/" + $name + " > "+$GUID

}

我真的不了解如何将内容中的读取导入XML格式。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

如果您的XML看起来像这样<doc><foo name='fooname'><bar>bar content</bar></foo></doc>,您可以像这样访问内容:

$MyXml = [xml](Get-Content $xmlFile)
$MyXml.doc.foo.name
$MyXml.doc.foo.bar

答案 1 :(得分:2)

尝试以下方法:

function list-xml-files() {
    get-childitem -recurse -force | ? { -not $_.psisdirectory } | ? { $_.name.endswith('.xml') } 
}

function list-data([xml]$xml) {
    $path = $xml.ExportedContentItem.path
    $name = $xml.ExportedContentItem.name
    $ID = $xml.ExportedContentItem.ID
    [string]::Format("{0}/{1} > {2}", $path, $name, $ID)
}

list-xml-files | % { [xml](get-content $_) } | ? { $_.ExportedContentItem } | % { list-data $_ }

此代码遵循更具功能性的编程风格。 '%'是map,'?'是filter

它展示了PowerShell的几个不错的功能。您可能需要install PowerShell 3.0(您还需要.NET 4.0),您将能够通过IntelliSense探索各种PowerShell功能。

答案 2 :(得分:0)

尝试读取单个xml文件路径时出错。我用$ _。fullname:

解决了这个问题
Get-ChildItem C:\Users\rasuser\Desktop\import *.xml -recurse | 
% { 
    $file = [xml](Get-Content $_.fullname)

    $path = $file.ExportedContentItem.path
    $name = $file.ExportedContentItem.name
    $GUID = $file.ExportedContentItem.ID

    $out = $path + "/" + $name + "`t" + $GUID

    $out
}
相关问题