简体   繁体   中英

Powershell load multiple XML

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM