0

Newbie to Powershell. I'd like to parse multiple files one after another. In order to do this, I need to load the files as a XML. This is my code so far:

 for ($i=0; $i -le 5; $i++) 
{ 
     $contents = Get-ChildItem -Path $path -Force -Recurse 
     File |Select-Object -First $i | Select-Object -Last 1 
     $fl = $contents.Name
     $xml.Load(".\downloads\Test\$fl")
 }

If I remove for ($i=0; $i -le 5; $i++) it works. But I need it to work with the for loop. Any ideas?

1
  • 1
    What is the purpose of that loop? Also, please state exactly what does not work. If you get any error messages, please include them. Commented Sep 7, 2022 at 10:05

3 Answers 3

2

you could do:

$filepaths = (get-childitem -Path C:\tmp -Recurse -Filter '*.xml').psPath

#XML per cast
$xmldocuments = @(
    $filepaths | %{
        [xml](get-content -path $_)
    }
)

Alternatively create a new xml object and use the load method

$xml = New-Object -TypeName xml
$xmldocuments = @(
    $filepaths | %{
        $xml.Load($_)
        $xml
    }
)

The Array xmlDocuments contains each xml document as element.

Sign up to request clarification or add additional context in comments.

1 Comment

The .Load() method is the only way that respects the encoding attribute of the XML file. The Get-Content method only succeeds by coincidence, i. e. when there is a BOM or the default encoding used by Get-Content happens to match the encoding attribute of the XML.
1

Solved it with this code:

$files = Get-ChildItem -LiteralPath ".\downloads\Test" 
$xml = New-Object System.Xml.XmlDocument
foreach ($file in $files) 
{
$xml.Load($file.FullName)
}

This enabled me to acess and encode every file in the folder.

1 Comment

lol, great work - i dont get it but ok
0

Assuming you'd like to actually pull data out of the files, I'd recommend using Select-XML.

Select-XML lets you query with XPath, and will return the file, xpath, and node (this might be handy if you need to take the file name into account for any reason).

# get all .xml files beneath downloads\test
Get-ChildItem -LiteralPath '\downloads\Test' -filter *.xml |
   Select-Xml -XPath . # Get the root node of each file

You can also get fairly specific with your -XPath:

$elementOfInterest = 'a'
# get all .xml files beneath downloads\test
Get-ChildItem -LiteralPath '\downloads\Test' -filter *.xml |
   Select-Xml -XPath "//$elementOfInterest" # Get any element of interest

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.