HtmlAgilityPack XPath大小写忽略

本文关键字:大小写 XPath HtmlAgilityPack | 更新日期: 2023-09-27 18:22:25

当我使用时

SelectSingleNode("//meta[@name='keywords']")

它不起作用,但当我使用原始文档中使用的相同情况时,效果很好:

SelectSingleNode("//meta[@name='Keywords']")

所以问题是如何设置忽略大小写?

HtmlAgilityPack XPath大小写忽略

如果实际值是未知情况,我认为您必须使用translate。我相信是:

SelectSingleNode("//meta[translate(@name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='keywords']")

这是破解,但它是XPath1.0中唯一的选项(除了与大写相反的选项)。

如果需要更全面的解决方案,可以为XPath处理器编写一个扩展函数,该函数将执行不区分大小写的比较。这是相当多的代码,但你只写一次。

在实现扩展后,您可以按照以下编写查询

"//meta[@name[Extensions:CaseInsensitiveComparison('Keywords')]]"

其中Extensions:CaseInsensitiveComparison是在下面的示例中实现的扩展函数。

注意:这没有经过很好的测试,我只是为了这个响应把它放在一起,所以不存在错误处理等!

以下是自定义XSLT上下文的代码,它提供了一个或多个扩展函数

using System;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml;
using HtmlAgilityPack;
public class XsltCustomContext : XsltContext
{
  public const string NamespaceUri = "http://XsltCustomContext";
  public XsltCustomContext()
  {
  }
  public XsltCustomContext(NameTable nt) 
    : base(nt)
  {    
  }
  public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes)
  {
    // Check that the function prefix is for the correct namespace
    if (this.LookupNamespace(prefix) == NamespaceUri)
    {
      // Lookup the function and return the appropriate IXsltContextFunction implementation
      switch (name)
      {
        case "CaseInsensitiveComparison":
          return CaseInsensitiveComparison.Instance;
      }
    }
    return null;
  }
  public override IXsltContextVariable ResolveVariable(string prefix, string name)
  {
    return null;
  }
  public override int CompareDocument(string baseUri, string nextbaseUri)
  {
    return 0;
  }
  public override bool PreserveWhitespace(XPathNavigator node)
  {
    return false;
  }
  public override bool Whitespace
  {
    get { return true; }
  }
  // Class implementing the XSLT Function for Case Insensitive Comparison
  class CaseInsensitiveComparison : IXsltContextFunction
  {
    private static XPathResultType[] _argTypes = new XPathResultType[] { XPathResultType.String };
    private static CaseInsensitiveComparison _instance = new CaseInsensitiveComparison();
    public static CaseInsensitiveComparison Instance
    {
      get { return _instance; }
    }      
    #region IXsltContextFunction Members
    public XPathResultType[] ArgTypes
    {
      get { return _argTypes; }
    }
    public int Maxargs
    {
      get { return 1; }
    }
    public int Minargs
    {
      get { return 1; }
    }
    public XPathResultType ReturnType
    {
      get { return XPathResultType.Boolean; }
    }
    public object Invoke(XsltContext xsltContext, object[] args, XPathNavigator navigator)
    {                
      // Perform the function of comparing the current element to the string argument
      // NOTE: You should add some error checking here.
      string text = args[0] as string;
      return string.Equals(navigator.Value, text, StringComparison.InvariantCultureIgnoreCase);        
    }
    #endregion
  }
}

然后,您可以在XPath查询中使用上述扩展函数,下面是我们的示例

class Program
{
  static string html = "<html><meta name='"keywords'" content='"HTML, CSS, XML'" /></html>";
  static void Main(string[] args)
  {
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(html);
    XPathNavigator nav = doc.CreateNavigator();
    // Create the custom context and add the namespace to the context
    XsltCustomContext ctx = new XsltCustomContext(new NameTable());
    ctx.AddNamespace("Extensions", XsltCustomContext.NamespaceUri);
    // Build the XPath query using the new function
    XPathExpression xpath = 
      XPathExpression.Compile("//meta[@name[Extensions:CaseInsensitiveComparison('Keywords')]]");
    // Set the context for the XPath expression to the custom context containing the 
    // extensions
    xpath.SetContext(ctx);
    var element = nav.SelectSingleNode(xpath);
    // Now we have the element
  }
}

我就是这样做的:

HtmlNodeCollection MetaDescription = document.DocumentNode.SelectNodes("//meta[@name='description' or @name='Description' or @name='DESCRIPTION']");
string metaDescription = MetaDescription != null ? HttpUtility.HtmlDecode(MetaDescription.FirstOrDefault().Attributes["content"].Value) : string.Empty;

或者使用新的Linq语法,它应该支持不区分大小写的匹配:

        node = doc.DocumentNode.Descendants("meta")
            .Where(meta => meta.Attributes["name"] != null)
            .Where(meta => string.Equals(meta.Attributes["name"].Value, "keywords", StringComparison.OrdinalIgnoreCase))
            .Single();

但是,为了防止NullReferenceException。。。