首页 > 解决方案 > Endless loop when read .xml-file

问题描述

I made a PowerShell script to read and write infos/settings to an .xml file.

Param(
    [string]$mode,
    [string]$set,
    [string]$xml
)

function readSettings([string]$xmlfile, [string]$setting)
{
    $s = readSettings $xmlfile
    $v = $s[$setting]
    Write-Host $v
}

function exportSettings([string]$xmlfile)
{
    $xmlDoc = New-Object XML
    $xmlDoc.Load($xmlfile)
    $settings = @{}
    $xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}
    return $settings
}

function importSettings([hashtable]$ht,[string]$xmlFile){
    $xmlDoc = New-Object XML
    $xmlDoc.Load($xmlFile)
    foreach ($key in $ht.keys){
        $settingNode = $xmlDoc.SelectSingleNode("/settings/setting[@name='$key']")
        if ($settingNode){
            $settingNode.firstChild.Value = $ht[$key]
        }else{
            $newNode = $xmlDoc.settings.setting[0].Clone()
            $newNode.name = $key
            $newNode.firstChild.Value = $ht[$key]
            $xmlDoc.settings.appendChild($newNode)
        }
    }
    $xmlDoc.Save($xmlFile)
}

if($mode -eq "read")
{
    readSettings($xml, $set)
}

if ($mode -eq "write")
{
}

(Also on GitHub.)

Whenever I read an .xml file, it generates an endless loop with RAM consumption up to 2GB.

I thought that

$xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}

could be the reason, but I don't know how to solve it. Writing to a xml-file works perfectly fine. Can anyone help?

标签: xmlpowershell

解决方案


I think that readSettings function call itself without test, and that's enough to loop I think.

function readSettings([string]$xmlfile, [string]$setting)
{
    $s = readSettings $xmlfile
    $v = $s[$setting]
    Write-Host $v
}

推荐阅读