Beispiel #1
0
        /// <summary>
        /// 尝试生成元素开始标签的HTML形式
        /// </summary>
        /// <param name="element">要生成HTML的元素</param>
        /// <param name="selfClosed">指示是否应产生自结束符号</param>
        /// <returns></returns>
        public static string GenerateTagHtml(IHtmlElement element, bool selfClosed)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }


            var builder = new StringBuilder(20);

            builder.Append("<");
            builder.Append(element.Name);

            foreach (var attribute in element.Attributes())
            {
                builder.Append(" ");
                builder.Append(attribute.Name);
                if (attribute.AttributeValue != null)
                {
                    if ((HtmlSpecification.IsUriValue(attribute) || HtmlSpecification.IsScriptValue(attribute)) && !attribute.AttributeValue.Contains('"'))
                    {
                        builder.Append("=\"").Append(attribute.AttributeValue).Append("\"");
                    }
                    else
                    {
                        builder.Append("=\"").Append(HtmlEncoding.HtmlAttributeEncode(attribute.AttributeValue)).Append("\"");
                    }
                }
            }

            if (selfClosed)
            {
                builder.Append(" /");
            }

            builder.Append(">");
            return(builder.ToString());
        }
Beispiel #2
0
        /// <summary>
        /// 将文档中所有的uri属性转换为绝对的uri。
        /// </summary>
        /// <param name="document">要执行转换的文档</param>
        /// <param name="resolveInternalReference">是否转换页内 uri</param>
        public static void ResolveUriToAbsoluate(this IHtmlDocument document, bool resolveInternalReference)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }


            var baseUri = document.DocumentUri;

            if (baseUri == null)
            {
                throw new InvalidOperationException();
            }

            foreach (var attribute in document.AllElements().SelectMany(e => e.Attributes()).Where(a => HtmlSpecification.IsUriValue(a)).ToArray())
            {
                var value = attribute.Value();
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                Uri uri;

                if (!Uri.TryCreate(baseUri, value, out uri))
                {
                    continue;
                }

                if (uri.Equals(baseUri) && !resolveInternalReference)
                {
                    continue;
                }


                attribute.Element.SetAttribute(attribute.Name, uri.AbsoluteUri);
            }
        }