将XML数据提取为excel

时间:2016-12-13 14:53:02

标签: xml excel vba

大家好,我发现这个代码可以帮助我从xml文档中提取数据。 此代码如下所示:

Function fnReadXMLByTags()
Dim mainWorkBook As Workbook
Set mainWorkBook = ActiveWorkbook
mainWorkBook.Sheets("Sheet1").Range("A:A").Clear
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
XMLFileName = "D:\Sample.xml"
oXMLFile.Load (XMLFileName)
Set TitleNodes = oXMLFile.SelectNodes("/catalog/book/title/text()")
Set PriceNodes = oXMLFile.SelectNodes("/catalog/book/price/text()")
mainWorkBook.Sheets("Sheet1").Range("A1,B1,C1").Interior.ColorIndex = 40
mainWorkBook.Sheets("Sheet1").Range("A1,B1,C1").Borders.Value = 1
mainWorkBook.Sheets("Sheet1").Range("A" & 1).Value = "Book ID"
mainWorkBook.Sheets("Sheet1").Range("B" & 1).Value = "Book Titles"
mainWorkBook.Sheets("Sheet1").Range("C" & 1).Value = "Price"
mainWorkBook.Sheets("Sheet1").Range("D1").Value = "Total books: " & TitleNodes.Length

    For i = 0 To (TitleNodes.Length - 1)
        Title = TitleNodes(i).NodeValue
        Price = PriceNodes(i).NodeValue
    mainWorkBook.Sheets("Sheet1").Range("B" & i + 2).Borders.Value = 1
    mainWorkBook.Sheets("Sheet1").Range("C" & i + 2).Borders.Value = 1
    mainWorkBook.Sheets("Sheet1").Range("B" & i + 2).Value = Title
    mainWorkBook.Sheets("Sheet1").Range("C" & i + 2).Value = Price
Next
'Reading the Attributes
Set Nodes_Attribute = oXMLFile.SelectNodes("/catalog/book")
For i = 0 To (Nodes_Attribute.Length - 1)
    Attributes = Nodes_Attribute(i).getAttribute("id")
    mainWorkBook.Sheets("Sheet1").Range("A" & i + 2).Borders.Value = 1
    mainWorkBook.Sheets("Sheet1").Range("A" & i + 2).Value = Attributes
Next
End Function

这对于看起来像这样的XML

非常有用
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
                                      with XML.</description>
   </book>

但是我的XML数据看起来更像是

<catalog>
   <cbc:book="bk101">
      <author>Gambardella, Matthew</author>
      <cac:title>XML Developer's Guide</cac:title>
      <genre>Computer</genre>
      <cac:price>44.95</cac:price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </cbc:book>

我尝试在代码中更改此部分:

Set TitleNodes = oXMLFile.SelectNodes("/catalog/book/cac:title/text()")
Set PriceNodes = oXMLFile.SelectNodes("/catalog/book/cac:price/text()")

cac和cbc似乎做了一些阻止代码工作的事情。 你知道我能做些什么来解决这个问题吗?感谢。

0 个答案:

没有答案