Geckofx从geckoelement获取xpath

时间:2014-08-18 06:32:15

标签: c# xulrunner geckofx

如何使用geckofx从geckoelement获取xpath?

private void webBrowser_DomClick(object sender, DomEventArgs e)
{
    GeckoElement clickedElement = e.Target.CastToGeckoElement();                      
}

如何获得clickedElement xPath?

1 个答案:

答案 0 :(得分:1)

    public static string GetSmallXpath(this GeckoNode node)
    {
        if (node.NodeType == NodeType.Attribute)
        {

            return String.Format("{0}/@{1}", GetSmallXpath(((GeckoAttribute)node).OwnerDocument), node.LocalName);
        }
        if (node.ParentNode == null)
        {
            return "";
        }
        string elementId = ((GeckoHtmlElement) node).Id;
        if (!String.IsNullOrEmpty(elementId))
        {
            return String.Format("//*[@id=\"{0}\"]", elementId);

        }


        int indexInParent = 1;
        GeckoNode siblingNode = node.PreviousSibling;

        while (siblingNode != null)
        {

            if (siblingNode.LocalName == node.LocalName)
            {
                indexInParent++;
            }
            siblingNode = siblingNode.PreviousSibling;
        }


        return String.Format("{0}/{1}[{2}]", GetSmallXpath(node.ParentNode), node.LocalName, indexInParent);
    }

    public static string GetXpath(this GeckoNode node)
    {
        if (node.NodeType == NodeType.Attribute)
        {

            return String.Format("{0}/@{1}", GetXpath(((GeckoAttribute)node).OwnerDocument), node.LocalName);
        }
        if (node.ParentNode == null)
        {

            return "";
        }


        int indexInParent = 1;
        GeckoNode siblingNode = node.PreviousSibling;

        while (siblingNode != null)
        {

            if (siblingNode.LocalName == node.LocalName)
            {
                indexInParent++;
            }
            siblingNode = siblingNode.PreviousSibling;
        }

        return String.Format("{0}/{1}[{2}]", GetXpath(node.ParentNode), node.LocalName, indexInParent);
    }