2

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?

Peck3277
  • 1,383
  • 8
  • 22
  • 46
  • 1
    possible duplicate of [How to read XML in Powershell?](http://stackoverflow.com/questions/18509358/how-to-read-xml-in-powershell) – Scott Solmer Oct 16 '13 at 16:04
  • 1
    You say your code works for one file, but you didn't say in which way it stops working when you apply it to several files in a loop. – Ansgar Wiechers Oct 16 '13 at 16:26
  • Sorry, I should have said I was navigating the XML correctly when using it on a single file using Get-Content rather than Get-ChildItem. When I try to loop the above code I'm unable read the XML content into $myXml – Peck3277 Oct 18 '13 at 11:24

3 Answers3

3

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
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
3

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.

ScalaWilliam
  • 733
  • 4
  • 16
0

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
}
Peck3277
  • 1,383
  • 8
  • 22
  • 46