2015-04-15 40 views
0
<?xml version="1.0"?> 
<catalog> 
<book id="Adventure"> 
    <author>Gambardella, Matthew</author> 
    <title>XML Developer's Guide</title> 
    <price>44.95</price> 
    <misc> 
     <Publisher id="5691"> 
      <PublisherLocation>Los Angeles</PublisherLocation> 
     </Publisher> 
     <PublishedAuthor fName="Gambardella"> 
      <StoreLocation>Store B</StoreLocation> 
     </PublishedAuthor> 
    </misc> 
</book> 
<book id="Adventure"> 
    <author>Ralls, Kim</author> 
    <title>Midnight Rain</title> 
    <price>5.95</price> 
    <misc> 
     <Publisher id="4787"> 
      <PublisherLocation>New York</PublisherLocation> 
     </Publisher> 
     <PublishedAuthor Name="Ralls"> 
      <StoreLocation>Store B</StoreLocation> 
     </PublishedAuthor> 
    </misc> 
</book> 
</catalog> 

PublishedAuthor的路徑是與一個字符除外兩本書一樣。是否可以爲此角色設置通配符,以便它可以接受XPath?VBA Xpath的通配符快報

<catalog/book/misc/PublishedAuthor[@fName=]/

產生了完全相同的結果爲:

<catalog/book/misc/PublishedAuthor[@Name=]/

回答

1

如果屬性名稱可以是NamefName那麼你可以使用:

Sub Tester() 
    Dim doc As New MSXML2.DOMDocument 
    Dim n 

    doc.LoadXML Range("a1").Value 

    Set n = doc.SelectNodes("/catalog/book/misc/PublishedAuthor[@Name='Ralls']|" & _ 
          "/catalog/book/misc/PublishedAuthor[@fName='Ralls']") 

    Debug.Print n.Length '>> 2 

End Sub 

有沒有通配符可用於屬性名稱。

+0

Thanks!但是如果它是該屬性之後的節點呢?從上面的示例中,說一些像' NRH

+0

對不起,我的意思是更像' NRH

1

在XPath中沒有專門針對字母的通配符。正如您可能已經意識到的那樣,通配符爲整個名稱(元素名稱或屬性名稱)工作。要在xpath中部分匹配,您可能需要考慮starts-with()substring()函數。

這種特定情況下可能的替代方案是用or運營商,這將節省您寫相同的路徑兩次,用工會時(|)運算符,如:

/catalog/book/misc/PublishedAuthor[@fName or @Name] 

和關於你的評論,你可以使用starts-with()檢查節點的name()像這樣:

/catalog/book/misc/*[starts-with(name(), 'PublishedAuthor')]/area/StoreLocation 
+0

有趣。我也可以在技術上做' NRH

+1

'contains(name(),'StoreLocation')'should also work,but'ends-with()'might not because it is xpath 2.0 function(AFAIK,most xpath engine /庫只實現了xpath 1.0)。參考:[xpath 1.0 spec](http://www.w3.org/TR/xpath/) – har07

+0

對不起,有一個問題,但我遇到了一個問題: Set loc = pn.SelectSingleNode(「misc/PublishedAuthor/contains(name(),'StoreLocation')」)'在這種情況下,VBA似乎不喜歡括號,當我刪除括號時VBA似乎不喜歡word **包含**。任何想法爲什麼?:(另外,我注意到很多其他在線用戶在聲明XPath時不使用「引號」,僅僅是爲了演示目的? – NRH