【问题标题】:How to retrieve specific information from XML type document如何从 XML 类型文档中检索特定信息
【发布时间】:2019-02-13 15:48:14
【问题描述】:

我正在 Excel 中处理 VBA 宏,以从 CNC 程序代码中收集信息。 到目前为止,我已经获得了材料类型、厚度、x 和 Y 尺寸以及使用的数量。

我现在正在尝试获取“切割长度” - 所以我可以在成本计算中使用它。

这是 XML 代码段:

<Info num="6" name="Tools">
      <MC machine="psys_ETN_5">
        <Tool name="TN901" length="16262.96209" time="53.72817301" cutoutArea="8138.657052"/>
      </MC>
    </Info>

有很多“信息”行。 可能有不止一个“工具”行,但我只追求“TN901”行。

我试图捕获的数据是 'Length="######.##"' 的值

我已经从这样的代码中捕获了我需要的所有其他内容:

<Material>316</Material>
      <SheetX>2000</SheetX>
      <SheetY>1000</SheetY>
      <Thickness>3</Thickness>
</Material>

使用这样的代码:

    For Each nodemat In XMLDataDrg.SelectNodes("//Material")
        Matl = nodemat.Text
        Worksheets("Sheet4").Range("H" & RowA).Value = Matl
    Next
    For Each nodesht In XMLDataDrg.SelectNodes("//Thickness")
        Thk = nodesht.Text
        Worksheets("Sheet4").Range("I" & RowA).Value = Thk
    Next

但是那种代码没有得到切割长度。

有什么帮助吗? :)

谢谢

西蒙

【问题讨论】:

标签: excel xml vba nodes


【解决方案1】:

在您的示例中,厚度保存为 XML 元素。
长度存储为 XML 属性。
(见https://www.xmlfiles.com/xml/xml-attributes/

要读取 XML 属性,请查看: Read XML Attribute VBA

根据那里提供的代码,您应该能够解决您的问题:

'Include a reference to Microsoft XML v3
Dim XMLDataDrg As DOMDocument30
Set XMLDataDrg = New DOMDocument30
XMLDataDrg.Load ("C:\...\sample.xml")

'...

Dim id As String
id = XMLDataDrg.SelectSingleNode("//Info/MC/Tool").Attributes.getNamedItem("length").Text

【讨论】:

    【解决方案2】:

    您可以使用 xpath 将属性 name 的值 TN901 限制为 Tool 元素,然后循环所有属性并写出。我正在从桌面上的文件中读取您的 XML。

    Option Explicit
    Public Sub test()
        Dim xmlDoc As Object
        Set xmlDoc = CreateObject("MSXML2.DOMDocument")
        With xmlDoc
            .validateOnParse = True
            .setProperty "SelectionLanguage", "XPath"
            .async = False
    
            If Not .Load("C:\Users\User\Desktop\Test.xml") Then
                Err.Raise .parseError.ErrorCode, , .parseError.reason
            End If
        End With
        Dim elem As Object, attrib As Object
    
        For Each elem In xmlDoc.SelectNodes("//Tool[@name='TN901']")
           For Each attrib In elem.Attributes
               Debug.Print attrib.nodeName, attrib.Text
           Next
        Next
    End Sub
    

    结果:

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多