function EnsureNavigationNode(
    [Microsoft.SharePoint.Navigation.SPNavigationNodeCollection] $nodes,
    [string] $title,
    [string] $url)
{
    Write-Debug "Ensuring navigation node ($title - $url)..."
        
    [Microsoft.SharePoint.Navigation.SPNavigationNode] $node =
        $nodes | Where-Object { $_.Url -eq $url -and $_.Title -eq $title }

    If ($node -eq $null)
    {
        Write-Debug "Creating new navigation node ($title - $url)..."

        $node = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode(
            $title,
            $url,
            $true)

        $null = $nodes.AddAsLast($node)
        $nodes.Navigation.Web.Update()
    }

    If ($node.Title -ne $title)
    {
        Write-Debug ("Updating title of navigation node ($($node.Title)) to" `
            + "($title)...")

        $node.Title = $title
        $node.Update()
    }

    return $node
}

function ImportNavigationNodes(
    [Microsoft.SharePoint.Navigation.SPNavigationNodeCollection] $nodes,
    [System.Xml.XmlNodeList] $navElements)
{
    [int] $position = 0

    foreach ($navElement in $navElements)
    {
        $title = $navElement.GetAttribute("title")
        $url = $navElement.GetAttribute("url")

        [Microsoft.SharePoint.Navigation.SPNavigationNode] $navigationNode =
            EnsureNavigationNode $nodes $title $url

        If ($position -eq 0)
        {
            $navigationNode.MoveToFirst($nodes)
        }
        Else
        {
            $navigationNode.Move($nodes, $nodes[$position - 1])
        }

        $position = $position + 1

        $childNodes = $navElement.SelectNodes("NavigationNode")
        If ($childNodes.Count -gt 0)
        {
            ImportNavigationNodes $navigationNode.Children $childNodes
        }
    }
}

function ImportNavigationMenu(
    [Microsoft.SharePoint.SPWeb] $web,
    [xml] $navigationXml)
{
    Write-Host "Importing navigation menu for site ($($web.Url))..."

	$nodes = $web.Navigation.TopNavigationBar

    $navElements = $navigationXml.SelectNodes("//Nodes/NavigationNode")

    If ($navElements.Count -gt 0)
    {
        ImportNavigationNodes $nodes $navElements
    }
    Else
    {
        Write-Host "No navigation nodes found to import."
    }
}