XPATH使用命名空间属性和SelectSingleNode属性

时间:2017-11-20 03:34:18

标签: xml excel-vba xpath namespaces vba

我有这个XML - 它是Excel Ribbon的_rels文件:

<GridLayout rows="50" columns="50, *" class="mainMenuItems">

set columns="(set column size) , (set column size) ".

我尝试使用<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/> <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/> <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/> <Relationship Id="cuID14" Type="http://schemas.microsoft.com/office/2007/relationships/ui/extensibility" Target="customUI/customUI14.xml"/> </Relationships> 通过检查其SelectSingleNode属性来检查最后一个Relationship元素是否存在,ID为&#34; cuID14&#34;的元素。如果Relationships元素没有xmlns属性,即如果我将第二行更改为Type,则代码可以正常工作。我试图正确地做到这一点并且无法使语法工作。这是我的Relationships>函数的代码,没有xmlns复杂功能:

SelectSingleNode

我发现了很多例子,但没有使用带有已定义命名空间的属性。我尝试过像Sub CheckForAttribute() Dim oXMLDoc As MSXML2.DOMDocument60 Dim oXMLElement As MSXML2.IXMLDOMElement Dim XmlRelsNamespace As String XmlRelsNamespace = "xmlns:rels='http://schemas.openxmlformats.org/package/2006/relationships'" Set oXMLDoc = New MSXML2.DOMDocument60 oXMLDoc.SetProperty "SelectionNamespaces", XmlRelsNamespace oXMLDoc.Load "C:\Users\doug\XPATH_TESTER.xml" 'The following line works if the Relationships element to just <Relationships> Set oXMLElement = oXMLDoc.SelectSingleNode("//Relationship[@Type='http://schemas.microsoft.com/office/2007/relationships/ui/extensibility']") End Sub ...

这样的事情

1 个答案:

答案 0 :(得分:2)

你第二次尝试非常接近。

而不是

//rels:Relationship[@rels:Type='http:...`

你应该使用

//rels:Relationship[@Type='http:...

因为属性不属于默认命名空间 - 只是元素。

另见: