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?

3
  • 1
    possible duplicate of How to read XML in Powershell? Commented Oct 16, 2013 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. Commented Oct 16, 2013 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 Commented Oct 18, 2013 at 11:24

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Also you might want to explicitly declare "$MyXml" as an XML like: [xml]$MyXml = Get-Content $xmlFile
Yeah, that would help. :-)
4

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.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.