How to export all directions to an XML file


This sample will show you how you can programmatically export all the directions to an XML file.

How to use

  1. Create a Route or Closest Facility analysis layer
  2. Add some network locations and click solve
  3. Paste this code into a VBA module in ArcMap
  4. Call the function ExportAllDirectionsToXMLFile()
[VBA]
'This sub uses the active analysis layer that has already been solved
'and outputs the Directions for the Routes (or CFRoutes) to a XML file.

Public Sub ExportAllDirectionsToXMLFile()
    On Error GoTo ErrorHandler
    
    'Get the Network Analyst Extension
    Dim pNetworkAnalystExtension As INetworkAnalystExtension
    Set pNetworkAnalystExtension = Application.FindExtensionByName("Network Analyst")
    
    If pNetworkAnalystExtension Is Nothing Then Exit Sub
    If pNetworkAnalystExtension.NAWindow Is Nothing Then Exit Sub
    If pNetworkAnalystExtension.NAWindow.ActiveAnalysis Is Nothing Then Exit Sub
    
    Dim pNAContext As INAContext
    Set pNAContext = pNetworkAnalystExtension.NAWindow.ActiveAnalysis.Context
    
    'Make sure you have a valid TraversalResult
    If Not pNAContext.Result.HasValidResult Then
        MsgBox "You must first click solve."
        Exit Sub
    End If
    
    'Figure out if this is a Route or Closest Facility and get the right feature class
    Dim pFClass As IFeatureClass
    If TypeOf pNAContext.Solver Is INARouteSolver Then
        Set pFClass = pNAContext.NAClasses.ItemByName("Routes")
    ElseIf TypeOf pNAContext.Solver Is INAClosestFacilitySolver Then
        Set pFClass = pNAContext.NAClasses.ItemByName("CFRoutes")
    Else
        MsgBox "Invalid Context"
    End If
    
    'Add all the routes to a esriSystem.ISet
    Dim pRouteSet As esriSystem.ISet
    Dim pCursor As ICursor
    Dim pRow As IRow
    Set pRouteSet = New esriSystem.Set
    Set pCursor = pFClass.Search(Nothing, False)
    Set pRow = pCursor.NextRow
    Do Until pRow Is Nothing
        pRouteSet.Add pRow
        Set pRow = pCursor.NextRow
    Loop
    
    'Get the Directions Agent from the NAContext
    Dim pNAStreetDirectionsAgent As INAStreetDirectionsAgent
    Set pNAStreetDirectionsAgent = pNAContext.Agents.ItemByName("StreetDirectionsAgent")
    
    'Generate Directions
    pNAStreetDirectionsAgent.Execute pRouteSet, New CancelTracker '
    
    'Save Directions to a file
    pNAStreetDirectionsAgent.DirectionsContainer.SaveAsXML "C:\Temp\Directions.xml"
    
    Exit Sub
ErrorHandler:
    MsgBox Err.Description
End Sub