Home » excel » Map Filtered XML to an Excel Table

Map Filtered XML to an Excel Table

Posted by: admin March 9, 2020 Leave a comment


I have the below code that maps an XML Schema to Excel Tables (as in ListObjects).

Sub MapXMLFieldsToExcelCells(wb As Workbook, sLOB As String)

'**    Name:        xmlFieldMap
'**    Purpose:     Maps fields of existing xlmMap (named "xmlData") to file
'**    Dependents:  TieXMLToExcel (remapping of xml file)
'**    Notes:

sProcName = "MapXMLFieldsToExcelCells"

With wb

    Dim xMap As XmlMap
    Set xMap = .XmlMaps(sLOB)

    Dim wsXMLMain As Worksheet

    Set wsXMLMain = .Worksheets("xml" & IIf(Left(.Name, 2) = "SA", "SA", "") & sLOB)

    Dim wsConfig As Worksheet
    Set wsConfig = .Worksheets("rConfig")

    With wsConfig

        Dim rNode As Range
        For Each rNode In .Range("xmlNodeMapping").Columns(1).Cells

            Dim sNodePath As String
            sNodePath = rNode & rNode.Offset(, 1)

            Dim sTable As String
            sTable = rNode.Offset(, 2)

            'only have this here in case node does not exist
            'caveat is that it will fail also if node is just written out wrong
            Application.DisplayAlerts = False
            'On Error Resume Next
            wsXMLMain.ListObjects(sTable).ListColumns(rNode.Offset(, 3).Value2).XPath.SetValue xMap, sNodePath
            'On Error GoTo ErrorReport
            Application.DisplayAlerts = True


    End With


End With

End Sub

(please ignore project specific lines here – there are not too many)

The code works great. I can map nodes and attributes of nodes if I pass a configuration sheet like this:

Xpath           Node    Table   Field
/root/d/p/t/    ar      tForms  AR
/root/d/p/t/    @n      tFormsa name

What I would like to do, if it’s possible, is to apply a filter on a node to only map certain elements of that node.

For example, based on correct syntax:

Xpath                       Node        Table   Field
/root/d/p/t[item='ar']/     type        tForms  type

Would only pull elements from node t that = ar.

I can’t get this to work and can’t find anything online. I could accept is that is not an option but wanted to ask before giving up on the approach.

How to&Answers: