excel VBA和XML,建立了一个处理数千个XML文件的函数

ca1c2owp  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(134)

我试着建立一个Excel函数来研究一些XML文件,(这些文件属于BI解决方案,并且有大量的XML文件,最好的方法似乎是开发一些宏来挖掘文件内部)
下面是一个XML示例:

<?xml version="1.0" encoding="UTF-8"?>
<job>
  <name>PROC_A</name>
  <entries>
    <entry>
      <name>Start</name>
      <type>SPECIAL</type>
    </entry>
    <entry>
      <name>Success</name>
      <type>SUCCESS</type>
    </entry>
    <entry>
      <name>ST_1</name>
      <type>JOB</type>
      <filename>$/ST/PROC_ST_1.kjb</filename>
    </entry>
    <entry>
      <name>DT_1</name>
      <type>JOB</type>
      <filename>$/DT/PROC_DT_1.kjb</filename>
    </entry>
    <entry>
      <name>ST_2</name>
      <type>JOB</type>
      <filename>$/ST/PROC_ST_2.kjb</filename>
    </entry>
  </entries>
</job>

那么,如果我可以调用一个函数得到:

  • '//名称')-〉创建一个新的文件
  • 如果您的文件不存在,请使用以下命令:

这就是我建造它的全部成功,
我想把funcion也称为:

  • 如果您的文件不存在,请使用以下方法:成功,工作,工作,工作
  • '我的文件','获取每个值','/条目/条目~文件名')-〉;; $/ST/PROC_ST_1.kjb;在此,您可以使用以下命令:$/ST/PROC_ST_2.kjb文件系统

但不确定如何处理代码的第三个“IF”
到目前为止,这是我已经构建的函数:

Function makeMAGIC(file, instruction, key) As Variant

    Dim FilePath As String
    Dim strOUTPUT As String
    Dim firstNode As String
    Dim oDocXML As MSXML2.DOMDocument60
    
    Set oDocXML = New MSXML2.DOMDocument60
    
   
    FilePath = "C:\...\"
    FilePath = FilePath & file
   
    
    oDocXML.Load FilePath
    
    If Right(file, 4) = ".ktr" Then
        firstNode = "transformation"
    ElseIf Right(file, 4) = ".kjb" Then
        firstNode = "job"
    Else
        strOUTPUT = "UNKNOWN FILE"
        GoTo EndFunction
    End If
    

    If instruction = "getVALUE" Then
        Set xVALUE = oDocXML.SelectSingleNode("/" & firstNode & key)
        strOUTPUT = xVALUE.Text
    End If
    
    If instruction = "getNumNodes" Then
        Set xNodeList = oDocXML.SelectNodes("/" & firstNode & Split(key, "~")(0))
        auxI = 0
        For Each xNodeMember In xNodeList
            auxI = auxI + 1
        Next
    strOUTPUT = CStr(auxI)
    End If
    
    If instruction = "get_DOING" Then
        Set xNodeList = oDocXML.SelectNodes("/" & firstNode & Split(key, "~")(0))
        auxI = 0
        For Each xNodeMember In xNodeList

            'xDetailNode = xNodeList.SelectSingleNode("/" & Split(key, "~")(0))  -> not working
           
        Next
    strOUTPUT = CStr(auxI)
    End If
    

EndFunction:
 Set oDocXML = Nothing
 makeMAGIC = strOUTPUT
End Function
z9gpfhce

z9gpfhce1#

“第三个如果”必须是:

If instruction = "getEachVALUE" Then
    Set xNodeList = oDocXML.SelectNodes("/" & firstNode & Split(key, "~")(0))
    auxI = 0
    For Each xNodeMember In xNodeList

        xDetailNode = xDetailNode & xNodeMember.text & ";"
       
    Next
strOUTPUT = CStr(xDetailNode)
End If

必须用类似于

Call makeMAGIC("test.kjb", "getEachVALUE", "/entries/entry/filename")

Call makeMAGIC("test.kjb", "getEachVALUE", "/entries/entry/name")

我希望这能成功!麦克斯

相关问题