gpt4 book ai didi

xml - 解析从 Microsoft Excel 导出的 XML 电子表格文件

转载 作者:行者123 更新时间:2023-12-04 21:36:16 25 4
gpt4 key购买 nike

我正在尝试使用 VBScript 解析从 Microsoft Excel 导出的 XML 电子表格文件。我首先尝试计算 <Row> 的数量元素。但是脚本总是返回 0。我做错了什么?

这是我的 VBScript 文件:

Set oXML = CreateObject("Microsoft.XMLDOM")

oXML.aSync = false
oXML.SetProperty "SelectionLanguage", "XPath"
oXML.SetProperty "ServerHTTPRequest", True
oXML.validateOnParse = False
oXML.resolveExternals = False

oXML.Load "_test_.xml"

MsgBox oXML.SelectNodes("//Row").length ' Return 0

WScript.Quit

' Looping through all nodes works fine
Set nodes = oXML.selectNodes("//*")    
For i = 0 to nodes.length -1 
    Msgbox nodes(i).nodeName
Next

这是 XML 文件:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Version>14.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG/>
</OfficeDocumentSettings>
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="2" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="15">
<Row ss:AutoFitHeight="0">
<Cell><Data ss:Type="String">First Row</Data></Cell>
</Row>
<Row ss:AutoFitHeight="0">
<Cell><Data ss:Type="String">Second Row</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook>

最佳答案

由于有多个命名空间,因此您必须为 XPATH 定义这些命名空间。即使对于默认命名空间也必须这样做。如果没有,您将无法使用 XPATH 从命名空间中获取具体元素。这就是为什么//*可以,但是 //Row将无法工作,因为 XPATH 不知道哪个命名空间 Row属于。

使用 setProperty Method 设置命名空间.另见 Second-Level DOM PropertiesSelectionNamespaces Property .

你的例子:

Set oXML = CreateObject("Microsoft.XMLDOM")

oXML.aSync = false
oXML.SetProperty "SelectionLanguage", "XPath"
oXML.SetProperty "ServerHTTPRequest", True
oXML.validateOnParse = False
oXML.resolveExternals = False

oXML.setProperty "SelectionNamespaces", "xmlns:d=""urn:schemas-microsoft-com:office:spreadsheet""" & _
" xmlns:o=""urn:schemas-microsoft-com:office:office""" & _
" xmlns:x=""urn:schemas-microsoft-com:office:excel""" & _
" xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""" & _
" xmlns:html=""http://www.w3.org/TR/REC-html40"""

oXML.Load "_test_.xml"

MsgBox oXML.SelectNodes("//d:Row").length ' Return 2

' Looping through all rows in Table
Set nodes = oXML.selectNodes("//d:Table//*")
For i = 0 to nodes.length -1
Msgbox nodes(i).nodeName
Next

在该示例中,我在默认命名空间前添加了 d .

关于xml - 解析从 Microsoft Excel 导出的 XML 电子表格文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com