顯示具有 XPath 標籤的文章。 顯示所有文章
顯示具有 XPath 標籤的文章。 顯示所有文章

2011/04/06

[C#][XPath] 模擬 XPath 的 max 與 min

在 XPath 中, 有兩個函式感覺會很常用, 但 C# 中卻沒 support. 那就是 max() 和 min().
少了這兩個函式, 每次想找 xml 資料中的最大/最小值, 就只能用 Linq 或是 Select 出所有標籤後, 在程式中去一個個比對.
其實 XPath 只要轉個彎, 就能做出類似的功能.

2011/01/27

[XPath][C#] 利用 XPath 的 contains 查詢特定的元素

透過 .Net 處理 XML 時, 有時會想要類似 SQL 裡的 IN (‘a’, b’, 'c’) 的查詢方式.
查一下 w3schools 的 XPath 函式庫, 可以發現一個 function 還蠻符合的:
fn:index-of((item,item,...),searchitem)
只是一套用到程式中, 就會產生以下的 Exception:
Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.
發生此問題的原因在於 .Net 並未完全支援 XPath 的函式, 有興趣的可以參考這個網址.

2010/08/06

[C#] XmlDocument 搭配 Linq 與 XPath

一般最常搭配 XML 用來查詢資料的技術是 XPath . 不過 .Net 僅支援到 XPath 1.0 , 有時想在 XPath 中加上日期函式的判斷都不行.
再加上若使用了 XPath 的函式或一些判斷式後, 整個 XmlDocument 的查詢效能會變慢. (參考以下的例子)
本文章所使用的 XML 內容 (ad.xml : 紀錄一些廣告圖與連結):

2010/07/28

[C#] 利用 Regex 或 XPath 查詢 xmlns, 並設定 XmlNamespaceManager

本文所使用的 XML 檔案 (ns.xml) 如下:
<?xml version="1.0" encoding="utf-8" ?>
<root>
  <h:table xmlns:h=http://www.w3.org/TR/html4/>
    <h:tr>
      <h:td>Apples</h:td>
      <h:td>Bananas</h:td>
    </h:tr>
  </h:table>
  <f:table xmlns:f="http://www.w3schools.com/furniture">
    <f:name>African Coffee Table</f:name>
    <f:width>80</f:width>
    <f:length>120</f:length>
  </f:table>
  <table>
    <name>Microsoft Visual C# 2008 Step by Step</name>
    <author>John Sharp</author>
  </table>
</root>

[C#] 利用 XPath 的 translate 函式查詢資料

XPath 中有一個函式: translate(string1,string2,string3)
w3schools 網站對其函式的說明: Converts string1 by replacing the characters in string2 with the characters in string3.
利用這個函式, 我們可以進行不區分大小寫的查詢 (如下):