Reputation: 1423
I am trying to extract some content from XML files. I have what I need working for one file but I need to do it for all files in a directory. So far what I have is:
$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
}
I'm not really understanding how to import read in the content to an XML format. Can anyone help me out?
Upvotes: 2
Views: 12188
Reputation: 1423
I was getting an error when trying to read the individual xml files path. I solved it by using $_.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
}
Upvotes: 0
Reputation: 201612
If your XML looks like this <doc><foo name='fooname'><bar>bar content</bar></foo></doc>
you access the content like so:
$MyXml = [xml](Get-Content $xmlFile)
$MyXml.doc.foo.name
$MyXml.doc.foo.bar
Upvotes: 3
Reputation: 741
Try the following:
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 $_ }
This code follows a more functional style of programming. '%' is a map
, '?' is a filter
.
It showcases several nice features of PowerShell. You might want to install PowerShell 3.0 (you need .NET 4.0 as well) and you will be able to explore the various PowerShell features via IntelliSense.
Upvotes: 3