使用Excel VBA解析多级XML输入

时间:2011-03-08 08:52:49

标签: xml excel vba parsing multidimensional-array

通常,需要使用Excel VBA从XML解析匹配某些过滤条件的输入。复杂性在于多级XML属性及其配对结果,必须在Excel中按顺序填充。

XML内容如下:

<Flow index="1" item="1" itemName="BB_150" ID="XXX">
      <Attribute name="FUNCTIONAL_X" dataType="Double" unit="" multiplier="" tag="YY">1</Attribute>
      <Attribute name="X_LOC" dataType="String" unit="" multiplier="" tag="YY">2</Attribute>
</Flow>
<Flow index="2" item="2" itemName="CC_200" ID="WWW">
      <Attribute name="FUNCTIONAL_X" dataType="Double" unit="" multiplier="" tag="YY">15</Attribute>
      <Attribute name="X_LOC" dataType="String" unit="" multiplier="" tag="YY">3</Attribute>
</Flow>
<Flow index="3" item="3" itemName="DD_200" ID="UUU">
      <Attribute name="FUNCTIONAL_X" dataType="Double" unit="" multiplier="" tag="YY">20</Attribute>
      <Attribute name="X_LOC" dataType="String" unit="" multiplier="" tag="YY">1</Attribute>
</Flow>
<Flow index="4" item="4" itemName="EE_115" ID="SSS">
      <Attribute name="FUNCTIONAL_X" dataType="Double" unit="" multiplier="" tag="YY">33</Attribute>
      <Attribute name="X_LOC" dataType="String" unit="" multiplier="" tag="YY">2</Attribute>
</Flow>
  1. 我如何只读取XML中以Attribute开头的那些节点?
  2. 选择了属性的所有节点后,将在Excel VBA中进一步解析。首先,查找name = X_LOC并获取值。
  3. 然后,查找name = FUNCTIONAL_X并检索值。
  4. 现在,需要将所有这些值放入工作表“结果”中的Excel列中。输出到Excel的格式如下:
  5. 列(从列A开始......然后继续到下一列..等)标题名称= X_LOC(按升序排序和显示) 行结果(以row1..then row2..etc开头)= FUNCTIONAL_X(每个配对X_LOC)

    填充到Excel中的结果应如下所示:

    A  B  C  D (Excel column)
    
    1  2  3  4 (X_LOC value)
    
    A1 B1 C1 D1 (Excel Row)
    
    1  15 20 33 (FUNCTIONAL_X value)
    

    注意:如果X_LOC重复相同的值,则不执行任何操作。保留现有的X_LOC&amp;它的FUNCTIONAL_X值。不需要覆盖。

1 个答案:

答案 0 :(得分:1)

在Excel中处理XML数据令人难以置信地很麻烦。我会坚持VBA。创建一个XML文档,如下所示,编辑它(使用XPath访问所需的节点/元素),然后保存它。

Set xmlInventory = CreateObject("Msxml2.DOMDocument.6.0")

文档: http://msdn.microsoft.com/en-us/library/ms756987%28v=VS.85%29.aspx

XPath教程: http://www.w3schools.com/xpath/default.asp