2016-04-22 73 views
0

我正在嘗試構建XPath查詢生成器,以使泛型代碼儘可能便攜。C#XML - XPath查詢生成器 - 動態創建查詢

到目前爲止,這是我想出了:

private static string XpathQueryBuilder (string NodeName,string AttributeName = null, string AttributeValue = null) 
    { 

     string XpathAttr = ""; 

     if (AttributeName != null) 
      if (AttributeValue != null) 
       XpathAttr = "[@" + AttributeName + "='" + AttributeValue + "']"; 
      else 
       XpathAttr = "[@" + AttributeName + "='*']"; 
     return "//" + NodeName + XpathAttr; 

    }  

我用這種方法看到的問題是,雖然如果我有一個以上的屬性或節點更多的,我想尋找了,這個功能將不起作用。有沒有辦法動態創建一個XPath查詢,可以在理論上接受任何數量的屬性和/或節點。

我的優先級是有一個函數接受多個屬性和屬性值,因爲這是比多個節點更可能的情況。

謝謝你的時間!

+0

爲什麼不傳遞一個KeyValuePair <字符串,字符串>,傳遞一個列表並通過追加屬性來遍歷它? – james31rock

+0

這將是一個很好的替代方案,而不是創建一個custome Linq提供程序。我不知道密鑰對機制。謝謝。 –

回答

2

您可以使用Dictionary<string,string>使能接收多個屬性參數的函數:

private static string XpathQueryBuilder(string nodeName, Dictionary<string,string> attributes = null) 
{ 
    string xpathAttr = ""; 
    if (attributes != null) 
    { 
     xpathAttr = 
      "[" + 
      String.Join(" and ", 
        attributes.Select(o => 
        { 
         var attrVal = o.Value ?? "*"; 
         return "@" + o.Key + "='" + attrVal + "'"; 
        }) 
      ) + "]"; 
    } 

    return "//" + nodeName + xpathAttr; 
} 

示例用法:

var node = "Root"; 
var attrs = new Dictionary<string, string> 
{ 
    {"foo", "bar"}, 
    {"baz", null}, 
}; 
var result = XpathQueryBuilder(node, attrs); 
Console.WriteLine(result); 

dotnetfiddle demo

輸出:

//Root[@foo='bar' and @baz='*'] 
+0

奇妙地爲我所需要的工作,謝謝。 –

1

您是否嘗試過使用LINQ to XML?

using System.Linq; 
using System.Xml; 
using System.Xml.Linq; 

String GUID = "something"; 

XElement profilesXel = XElement.Load("your xml file path"); 
XElement currProfile = (from el in profilesXel 
         where (String)el.Element("GUID") == GUID 
         select el).First(); 

....

+0

你能在你的回答中更具體嗎?我很難弄清楚這一點,我必須誠實地說,我不知道Linq圖書館從哪裏開始。 –

+0

我已更新我的答案,希望這有助於 –

+0

感謝您的更新。 –

1

您可以使用LINQ to XML

它可以讓你選擇你想要的任何數據。

此外,如果您需要更通用的解決方案,您可以嘗試執行your own LINQ Provider

第二種方法比第一種方法更復雜,但是因此您將有更通用的解決方案,它將通過LINQ鏈和表達式(lambda等)提供對xml文件的訪問。

舉例幾個環節的幫助:

http://weblogs.asp.net/mehfuzh/writing-custom-linq-provider

http://fairwaytech.com/2013/03/writing-a-custom-linq-provider-with-re-linq/

http://jacopretorius.net/2010/01/implementing-a-custom-linq-provider.html

https://aashishkoirala.wordpress.com/2014/03/10/linq-provider-1/

+0

感謝您的鏈接,我一定會研究LINQ to XML庫,但現在,它感覺有點過分,我覺得我可以管理,所以我會用字典的方法去。 –

+0

當然,我現在不強迫你跳進去。我很樂意幫助您瞭解LINQ to XML。或者如果你決定實施你自己的提供商 - 隨時提問! – MaKCbIMKo