Forum Discussion
Why do I get name printed 3 times instead of 2?
Hi , here's my code:
Add-Type -AssemblyName System.Web
$fileInGpx = "b.gpx"
[hashtable]$wptsUnique = @{}
[xml]$xml = Get-Content -Path $fileInGpx -Encoding UTF8
function trySetWptColor($wpti, $wptExisting)
{
Write-Host $wpti.name
}
$nsManager = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsManager.AddNamespace("osmand", "https://osmand.net")
$nsManager.AddNamespace("gpx", "http://www.topografix.com/GPX/1/1")
$XPath = "//gpx:wpt"
$wpts = $xml.selectNodes($XPath, $nsManager)
foreach($wpt in $wpts)
{
$wpt2 = $null
$lat2 = $wpt.lat -as [double]
$lon2 = $wpt.lon -as [double]
$key = $lat2 + '' + $lon2
if ($wptsUnique.ContainsKey($key))
{
$wptExisting = $wptsUnique[$key]
Write-Host $wpt.name
trySetWptColor($wpt, $wptExisting)
}
else
{
$wpt2 = @{
lat = 1
lon = 2
name = $wpt.name
extensions = "qqq"
}
$wptsUnique.add($key, $wpt2)
}
}
Here's the file it's supposed to read:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<gpx
xmlns='http://www.topografix.com/GPX/1/1'
xmlns:osmand='https://osmand.net'
>
<metadata>
<name>MOSTIKI</name>
</metadata>
<wpt lat="55.9840704" lon="36.6401806">
<name>AAAAAA</name>
<type>MOSTIKI</type>
<extensions>
<osmand:address>BBBBBB</osmand:address>
<osmand:icon>special_star</osmand:icon>
<osmand:background>circle</osmand:background>
<osmand:color>#eecc22</osmand:color>
</extensions>
</wpt>
<wpt lat="55.98407" lon="36.640181">
<name>CCCCC</name>
<type>MOSTIKI</type>
<extensions>
<osmand:address>DDDDD</osmand:address>
<osmand:icon>bridge_structure_suspension</osmand:icon>
<osmand:background>circle</osmand:background>
<osmand:color>#eecc22</osmand:color>
</extensions>
</wpt>
</gpx>
As a result of running I get this:
CCCCC
CCCCC AAAAAA
Why do I get CCCC AAAAA instead of just CCCCC
senglorychange line 34 to:
trySetWptColor $wpt $wptExisting
Passing multiple arguments to a function in PowerShell should not use commas to separate them, and function calls should not use parentheses. By using a comma, you are actually passing two variables merged into a single array ($wpti) whose first element is of type System.Xml.XmlElement and whose second element is a hashtable. The second variable ($wptExisting) is null. On line 12, Write-Host was writing all elements of the array that had a property called Name.
- MMeyer260Copper Contributor
senglorychange line 34 to:
trySetWptColor $wpt $wptExisting
Passing multiple arguments to a function in PowerShell should not use commas to separate them, and function calls should not use parentheses. By using a comma, you are actually passing two variables merged into a single array ($wpti) whose first element is of type System.Xml.XmlElement and whose second element is a hashtable. The second variable ($wptExisting) is null. On line 12, Write-Host was writing all elements of the array that had a property called Name.