Home > Mobile >  GetElement by multiple element types and class
GetElement by multiple element types and class

Time:06-01

what would be the xPath equiverlent of the css selector "div.foo, a, li.bar"

I currently have 2 functions written in c# to select elements by multiple selectors and classes:

        // returns the right way for Xpath 1.0 to check for class
        public static string GetHasClass(string className)
        {
            className = className.Trim();
            if (className.Contains(' '))
            {
                return string.Join("", className.Split(' ').Select(c => GetHasClass(c)));
            }

            return $"[contains(concat(' ', normalize-space(@class), ' '), ' {className} ')]";
        }

        // this function changes this: "div a li" to "*[self::div or self::a or self::li]"
        public static string GetSelectors(string csv)
        {
            string result = "";
            var types = csv.Split(" ");

            for (int i = 0; i < types.Length; i  )
            {
                result  = $"self::{types[i]}";

                //dont add the or in the last iteration
                if (i   1 < types.Length)
                    result  = " or ";
            }

            return $"*[{result}]";
        }

with these functions I can chain them together to get *[self::div or self::a or self::li][contains(concat(' ', normalize-space(@class), ' '), ' foo ')]

but this is the equiverlent of "div.foo, a.foo, li.foo"

To make it clear: I am not asking for a C# solution for my problem, im just asking how this css selector "div.foo, a, li.bar" can be written in XPath-1.0 because I dont know.

CodePudding user response:

If you want equivalent of "div.foo, a, li.bar" try

//div[@class='foo'] | //a | //li[@class='bar']

CodePudding user response:

"div.foo, a, li.bar" => "*[self::div[contains(concat(' ', normalize-space(@class), ' '), ' foo ')] or self::a or self::li[contains(concat(' ', normalize-space(@class), ' '), ' bar ')]]"

  • Related