【问题标题】:How can I get all HTML attributes with GeckoFX/C#如何使用 GeckoFX/C# 获取所有 HTML 属性
【发布时间】:2014-05-11 07:42:23
【问题描述】:

在 C# viaGeckoFx 中,我还没有找到查找元素所有属性的方法。

为此,我做了一个JavaScript函数。这是我的代码

GeckoWebBrowser GeckoBrowser = ....;
GeckoNode NodeElement = ....; // HTML element where to find all HTML attributes 

string JSresult = "";
string JStext = @"
function getElementAttributes(element) 
{
    var AttributesAssocArray = {};
    for (var index = 0; index < element.attributes.length; ++index) { AttributesAssocArray[element.attributes[index].name] = element.attributes[index].value; };
    return JSON.stringify(AttributesAssocArray);
} 

getElementAttributes(this);
";

using (AutoJSContext JScontext = new AutoJSContext(GeckoBrowser.Window.JSContext)) { JScontext.EvaluateScript(JStext, (nsISupports)NodeElement.DomObject, out JSresult); }

您是否有其他建议可以在 C#(不使用 Javascript)中实现这一点?

【问题讨论】:

    标签: c# javascript gecko geckofx


    【解决方案1】:

    GeckoElement.Attributes 属性允许访问元素的属性。

    例如(这是未经测试和未编译的代码):

    public string GetElementAttributes(GeckoElement element)
    {
       var result = new StringBuilder();
       foreach(var a in element.Attributes)
       {
           result.Append(String.Format(" {0} = '{1}' ", a.NodeName, a.NodeValue));
       }
    
       return result.ToString();
    }
    

    【讨论】:

    • 感谢您的帮助,Tom 但我在foreach(var a in element.Attributes) 中得到了System.InvalidCastException。例外是Unable to cast COM object of type 'System.__ComObject' to interface type 'Gecko.nsIDOMAttr
    • 我刚刚用 geckofx 29 测试了代码,它对我有用。 (更新次要代码错字后)。您使用的是什么版本的 geckofx?您是否使用匹配的 xulrunner/firefox 版本。
    • 我使用了 29.0.0.2 版本的 Geckofx-Core.dll 和 Geckofx-Winforms.dll。我更新到版本 29.0.0.4。没关系。
    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多