2016-04-22 74 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