Created
October 21, 2013 04:34
-
-
Save samirahmed/7078700 to your computer and use it in GitHub Desktop.
Html/Css queries to Xpath helper methods in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace CssPath | |
{ | |
public static class By | |
{ | |
public const string AnchorTag = "a"; | |
public const string AnyNode = "*"; | |
public enum Comparison | |
{ | |
Presence, | |
Equality, | |
Contains, | |
StartsWith, | |
EndsWith, | |
} | |
public static string XPath(string xpath) | |
{ | |
return xpath; | |
} | |
public static string Tag(string tagName) | |
{ | |
return string.Format(@"//{0}", tagName); | |
} | |
public static string Id(string id) | |
{ | |
return XPath(Comparison.Equality, "id", id); | |
} | |
public static string ClassName(string name, Comparison type = Comparison.Equality) | |
{ | |
return XPath(type, "class", name); | |
} | |
public static string Link(string linkText, Comparison comparisonType = Comparison.Equality) | |
{ | |
return XPath(comparisonType ,"href", linkText, AnchorTag); | |
} | |
public static string PartialLink(string linkText) | |
{ | |
return Link(linkText, Comparison.Contains); | |
} | |
public static string Attribute(string attribute, string name, Comparison comparisonType = Comparison.Equality, string node = null) | |
{ | |
return XPath(comparisonType, attribute, name, node); | |
} | |
private static string XPath(Comparison compareBy, string attribute, string name = "", string node = null) | |
{ | |
switch(compareBy) | |
{ | |
case Comparison.Equality: | |
return string.Format(@"//{0}[@{1}]", node ?? AnyNode); | |
case Comparison.Presence: | |
return string.Format(@"//{0}[@{1}=""{2}""]", node ?? AnyNode, attribute, name); | |
case Comparison.Contains: | |
return XpathFunction(node, "contains", attribute, name); | |
case Comparison.StartsWith: | |
return XpathFunction(node, "starts-with", attribute, name); | |
case Comparison.EndsWith: | |
return XpathFunction(node, "ends-with", attribute, name); | |
default: | |
return string.Empty; | |
} | |
} | |
private static string XpathFunction(string node, string func, string attr, string name) | |
{ | |
return string.Format(@"//{0}[{1}(@{2}=""{3}"")]", node ?? AnyNode, func, attr, name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment