当前位置: 首页>>代码示例>>C#>>正文


C# HtmlNode.SetAttributeValue方法代码示例

本文整理汇总了C#中HtmlAgilityPack.HtmlNode.SetAttributeValue方法的典型用法代码示例。如果您正苦于以下问题:C# HtmlNode.SetAttributeValue方法的具体用法?C# HtmlNode.SetAttributeValue怎么用?C# HtmlNode.SetAttributeValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HtmlAgilityPack.HtmlNode的用法示例。


在下文中一共展示了HtmlNode.SetAttributeValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SetValue

        public bool SetValue(HtmlNode n, string value)
        {
            if (n is HtmlNode && n.Name == "select")
            {
                foreach (HtmlNode o in n.SelectNodes("option"))
                {
                    o.SetAttributeValue("selected", o.GetAttributeValue("value", "").Equals(value) ? "selected" : "");
                }
                return true;
            }

            if (n is HtmlNode && n.Name == "input")
            {
                switch (n.GetAttributeValue("type", ""))
                {
                    case "radio":
                        n.SetAttributeValue("checked", n.GetAttributeValue("value", "").Equals(value) ? "checked" : "");
                        break;
                    default:
                        n.SetAttributeValue("value", value);
                        break;
                }
                n.SetAttributeValue("value", value);
                return true;
            }

            return false;
        }
开发者ID:tomgrv,项目名称:PA.SimiliBrowser,代码行数:28,代码来源:HtmlHandler.cs

示例2: GetExternalReference

        private static ExternalReference GetExternalReference(HtmlNode externalReferenceNode, int index)
        {
            string referenceUrl = externalReferenceNode.GetAttributeValue("href", string.Empty);
            string referenceId = GetExternalReferenceId(index);

            externalReferenceNode.InnerHtml = string.Format("[{0}]", index);
            externalReferenceNode.SetAttributeValue("href", "#" + referenceId);
            externalReferenceNode.SetAttributeValue("name", referenceId + BackLinkReferenceIdSuffix);

            return new ExternalReference { Index = index, Url = referenceUrl };
        }
开发者ID:sebnilsson,项目名称:WikiDown,代码行数:11,代码来源:ExternalReferencesConverterHook.cs

示例3: EachImages

 /// <summary>
 /// 递归遍历内容中的图片
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public static void EachImages(HtmlNode node, string baseUri = "")
 {
     //判断是否有子标签
     if (node.HasChildNodes)
         foreach (HtmlNode nn in node.ChildNodes)
             EachImages(nn, baseUri);
     else if (node.Name == "img")
     {
         //图片
         string url = node.GetAttributeValue("src", "");
         if (url == "") return;
         //获取图片信息,生成新的路径
         //getimages/{Year}/{Week}/{FileName}
         string exe = Path.GetExtension(url).TrimStart(new char[] { '.' });
         string fileName = Guid.NewGuid().ToString() + "." + exe;
         int day = DateTime.Now.Day;
         //相对路径
         string fullName = string.Format("autoimages\\{0}\\{3}\\{1}\\{2}." + exe, DateTime.Now.Year, day <= 10 ? 1 : (day <= 20 ? 2 : 3), Guid.NewGuid().ToString(), DateTime.Now.Month);
         //网站
         string urlNew = "/" + fullName.Replace("\\", "/");
         node.SetAttributeValue("src", urlNew);
         //保存到本地
         Uri uri = baseUri == "" ? new Uri(url) : new Uri(new Uri(baseUri), url);
         SaveImg(uri.AbsoluteUri, fullName);
     }
 }
开发者ID:abduwaris,项目名称:NewsGet,代码行数:31,代码来源:Html.cs

示例4: UpdateInlineStyleForElement

        /// <summary>
        /// Updates the inline styles for a given HTML node
        /// </summary>
        /// <param name="element">The HTML node to update inline styles for</param>
        /// <param name="declaration">The CSS declaration containing the styles to update the HTML node with</param>
        public static void UpdateInlineStyleForElement(HtmlNode element, Declaration declaration)
        {
            var style = element.GetAttributeValue("style", String.Empty);

            if (!HasDeclarationDefinedInline(declaration, style))
            {
                style += String.Format("{0}{1};", style == String.Empty ? String.Empty : " ", declaration);
            }
            else
            {
                var regex = new Regex(string.Format(@"(?<={0}:\s)(.*?)(?=;)", declaration.Name));
                style = regex.Replace(style, declaration.Expression.ToString());
            }

            element.SetAttributeValue("style", style);
        }
开发者ID:pmarflee,项目名称:postal,代码行数:21,代码来源:CSSInliner.cs

示例5: PopulateIssueInfoNode

        public void PopulateIssueInfoNode(HtmlNode issueInfoNode, HtmlNode kesiNode, HtmlNode mdNode)
        {
            string status = GetNodeInnerText(kesiNode, "./s:issueStatus", null);
            if (status != null)
                issueInfoNode.SetAttributeValue("status", status.EncodeXMLString());
            string resolution = GetNodeInnerText(kesiNode, "./s:issueResolution", null);
            if (resolution != null)
                issueInfoNode.SetAttributeValue("resolution", resolution.EncodeXMLString());
            string productName = GetNodeInnerText(kesiNode, "./s:issueProduct/s:productId", null);
            if (productName != null && GetNodeInnerText(kesiNode, "./s:issueActivity/s:activityWhat", "Product") == "Product")
                issueInfoNode.SetAttributeValue("productName", productName.EncodeXMLString());
            string componentName = GetNodeInnerText(kesiNode, "./s:issueProduct/s:productComponentId", null);
            if (componentName != null && GetNodeInnerText(kesiNode, "./s:issueActivity/s:activityWhat", "Component") == "Component")
                issueInfoNode.SetAttributeValue("componentName", componentName.EncodeXMLString());

            string priority = GetNodeInnerText(kesiNode, "./s:issuePriority", null);
            if (priority != null)
                issueInfoNode.SetAttributeValue("priority", priority.EncodeXMLString());
            string severity = GetNodeInnerText(kesiNode, "./s:issueSeverity", null);
            if (severity != null)
                issueInfoNode.SetAttributeValue("severity", severity.EncodeXMLString());

            string systemOS = GetNodeInnerText(kesiNode, "./s:issueComputerSystem/s:computerSystemOS", null);
            if (systemOS != null)
                issueInfoNode.SetAttributeValue("systemOS", systemOS.EncodeXMLString());
            string systemPlatform = GetNodeInnerText(kesiNode, "./s:issueComputerSystem/s:computerSystemPlatform", null);
            if (systemPlatform != null)
                issueInfoNode.SetAttributeValue("systemPlatform", systemPlatform.EncodeXMLString());
            string productVersion = GetNodeInnerText(kesiNode, "./s:issueProduct/s:productVersion", null);
            if (productVersion != null)
                issueInfoNode.SetAttributeValue("productVersion", productVersion.EncodeXMLString());

            string assignedToName = GetIssueAssignedTo(kesiNode);
            string assignedToUri = GetNodeInnerText(mdNode, "./o:issueAssignedToUri", null);
            if (!string.IsNullOrEmpty(assignedToName)) {
                HtmlNode assignedToNode = issueInfoNode.OwnerDocument.CreateElement("assignedTo");
                issueInfoNode.AppendChild(assignedToNode);
                assignedToNode.SetAttributeValue("name", assignedToName.EncodeXMLString());
                if (!string.IsNullOrEmpty(assignedToUri))
                    assignedToNode.SetAttributeValue("uri", assignedToUri.EncodeXMLString());
            }
            string CCName = GetIssueCCPerson(kesiNode);
            string CCUri = GetNodeInnerText(mdNode, "./o:issueCCPerson", null);		// todo: change this to the right value
            if (!string.IsNullOrEmpty(CCName)) {
                HtmlNode assignedToNode = issueInfoNode.OwnerDocument.CreateElement("CC");
                issueInfoNode.AppendChild(assignedToNode);
                assignedToNode.SetAttributeValue("name", CCName.EncodeXMLString());
                if (!string.IsNullOrEmpty(CCUri))
                    assignedToNode.SetAttributeValue("uri", CCUri.EncodeXMLString());
            }
        }
开发者ID:AlertProject,项目名称:Text-processing-bundle,代码行数:51,代码来源:KEUI.Indexing.cs

示例6: XslToHTML

        public void XslToHTML()
        {
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(styleSheetFile);
            transform.Transform(xmlFile, HttpContext.Current.Server.MapPath("/tmp") + "/Formulario.html");
            htmlDoc.Load("C:\\Form1\\Formulario.html");
            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//span[@class='xdTextBox']"))
            {
                node.Name = "input";
            }

            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//div[@class='xdDTPicker']"))
            {
                node.Name = "input";
                foreach (HtmlNode node2 in node.ChildNodes)
                {
                    if (node2.Name.Equals("span"))
                    {
                        node.SetAttributeValue("xd:binding", node2.Attributes["xd:binding"].Value);
                        node.SetAttributeValue("onclick", "setFecha(this)");
                    }
                }
                node.RemoveAllChildren();
                HtmlAttribute attr = htmlDoc.CreateAttribute("type", "date");
                node.Attributes.Prepend(attr);
                node.SetAttributeValue("style", "width: 100%;");

                node.SetAttributeValue("onclick", "setFecha(this)");

            }
            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//input | //select"))
            {
                node.SetAttributeValue("id", (idCounter++).ToString());
                if (node.Attributes["type"]!=null &&node.Attributes["type"].Value.Equals("button"))
                {
                    node.SetAttributeValue("onclick", "save()");
                }
            }

            HtmlNode head = htmlDoc.DocumentNode.SelectSingleNode("//head");
            HtmlNode body = htmlDoc.DocumentNode.SelectSingleNode("//body");
            HtmlNode meta = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            HtmlNode script = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);

            script = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            script.Name = "script";
            script.Attributes.Add("type", "text/javascript");
            script.SetAttributeValue("src", "tmp.js");
            head.ChildNodes.Add(script);

            meta.Name = "meta";
            meta.Attributes.Add("content", "width=device-width");
            head.ChildNodes.Add(meta);
            meta = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            meta.Name = "meta";
            meta.Attributes.Add("property", "maxid");
            meta.Attributes.Add("content", idCounter.ToString());
            head.ChildNodes.Add(meta);

            HtmlNode link = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            link.Name = "link";
            link.Attributes.Add("href", "common/bootstrap-responsive.min.css");
            head.ChildNodes.Add(link);
            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//body/div"))
            {
                node.Attributes.Add("class", "row-fluid");
            }
            this.addSpan(htmlDoc);

            htmlDoc.Save("C:\\Form1\\Formulario.html");
            idCounter = 0;
        }
开发者ID:josev55,项目名称:InfoParser,代码行数:72,代码来源:XMLParser.cs

示例7: BuildAttributeString

        static string BuildAttributeString(HtmlNode node)
        {
            string name = node.Name.ToLower();

            if (name == "a") {
                node.SetAttributeValue("href", SanitizeAHref(node.GetAttributeValue("href", String.Empty)));

                // Don't allow custom titles (tooltips), and make sure one is always set.
                node.SetAttributeValue("title", node.GetAttributeValue("href", String.Empty));

                Console.WriteLine("SET ATTRIBUTE VALUE !! " + node.GetAttributeValue("title", "frak"));
            }

            if (name == "img") {
                node.SetAttributeValue("src", SanitizeImgSrc(node.GetAttributeValue("src", String.Empty)));

                // FIXME:

                // Show something if the image fails to load for some reason.
                //node.SetAttributeValue("alt", "[IMAGE]");

                // Force width
                //node.SetAttributeValue("width", "100%");

                // Remove height
                //node.SetAttributeValue("height", String.Empty);
            }

            var attributeStringBuilder = new StringBuilder();
            foreach (var attr in node.Attributes) {
                string attrName = attr.Name.ToLower();
                string attrVal = attr.Value;
                Console.WriteLine(attrName);
                if (s_WhiteList[name] != null && s_WhiteList[name].Contains(attrName)) {
                    if (attributeStringBuilder.Length > 0)
                        attributeStringBuilder.Append(" ");
                    attributeStringBuilder.AppendFormat("{0}=\"{1}\"", attrName, attrVal);
                } else if (attrName == "style") {
                    // FIXME: Special handling for css
                }
            }
            if (attributeStringBuilder.Length > 0)
                attributeStringBuilder.Insert(0, " ");
            return attributeStringBuilder.ToString();
        }
开发者ID:jrudolph,项目名称:synapse,代码行数:45,代码来源:HtmlSanitizer.cs

示例8: WriteTranslatedText

 private void WriteTranslatedText(HtmlNode node, string text)
 {
     if (node.NodeType == HtmlNodeType.Text)
     {
         node.InnerHtml = text;
     }
     else if (node.NodeType == HtmlNodeType.Element && node.Name.ToLower() == "input")
     {
         node.SetAttributeValue("value", text);
     }
 }
开发者ID:MikePennington,项目名称:AutoWebTranslator,代码行数:11,代码来源:TranslationFilter.cs

示例9: TranslateUrlAttribute

 private static void TranslateUrlAttribute(HtmlNode node, string attrName, string oldBaseUrl, string newBaseUrl)
 {
     if (node != null)
     {
         string url = node.GetAttributeValue(attrName, null);
         if (!url.IsNullOrWhitespace())
         {
             url = url.Trim();
             if (!url.Contains(':') && !url.StartsWith("/", StringComparison.InvariantCultureIgnoreCase))
             {
                 string absUrl = Utils.CombineUrls(oldBaseUrl, url);
                 if (!absUrl.StartsWith(".."))
                 {
                     string newRelUrl = Utils.MakeRelativeUrl(newBaseUrl, absUrl);
                     node.SetAttributeValue(attrName, newRelUrl);
                 }
             }
         }
     }
 }
开发者ID:janzich,项目名称:dreamweaverer,代码行数:20,代码来源:Replacer.cs

示例10: InlineDeclarations

        /// <summary>
        /// Takes a list of css declarations, like color:white, and puts them in the element's style attribute.  Certain cases are treated special.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="declarations"></param>
        /// <remarks>
        /// Special Cases:
        /// img: width & height attributes
        /// td: align & valign
        /// table: cellspacing, border, and padding
        /// </remarks>
        public static void InlineDeclarations(HtmlNode element, List<CssDeclaration> declarations)
        {
            HtmlAttribute style = element.Attributes["style"];
            StringBuilder styleVal = null;
            HashSet<string> existingStyles = null; //so we don't overwrite any preexisting inline styles
            if (style != null)
            {
                existingStyles =
                    new HashSet<string>(CssParser.ParseDeclarations(style.Value).Select(dec => dec.Property));
                if (existingStyles.Count > 0)
                {
                    styleVal = new StringBuilder(style.Value.Trim());
                    if (styleVal[styleVal.Length - 1] != ';')
                        styleVal.Append(';');
                }
            }

            string tagName = element.Name.ToLowerInvariant();
            foreach (var declaration in declarations)
            {
                if (existingStyles != null && existingStyles.Contains(declaration.Property))
                    continue; //ignore the duplicate

                if (tagName.EqualsCaseInsensitive("td"))
                {
                    if (declaration.Property.EqualsCaseInsensitive(CssProperties.TextAlign))
                    {
                        if (!InlineNonStyleAttribute(element, "align", declaration.Value))
                            continue;
                    }
                    else if (declaration.Property.EqualsCaseInsensitive(CssProperties.VerticalAlign))
                    {
                        if (!InlineNonStyleAttribute(element, "valign", declaration.Value))
                            continue;
                    }
                }

                if (tagName.EqualsAny("table", "td", "img") &&
                    declaration.Property.EqualsAny(CssProperties.Width, CssProperties.Height))
                {
                    if (!InlineNonStyleAttribute(element, declaration.Property, declaration.Value))
                        continue;
                }
                if (tagName.EqualsAny("table") && declaration.Property.EqualsAny(CssProperties.BackgroundColor))
                {
                    if (!InlineNonStyleAttribute(element, "bgcolor", declaration.Value))
                        continue;
                }

                //a nice way to auto insert cellpadding and cellspacing
                if (declaration.Property.StartsWith("-attr-"))
                {
                    InlineNonStyleAttribute(element, declaration.Property.Strip("-attr-"), declaration.Value);
                    continue;
                }
                if (styleVal == null)
                    styleVal = new StringBuilder();

                styleVal.Append(declaration.Property + ":" + declaration.Value + ";");
            }

            if (styleVal != null)
                element.SetAttributeValue("style", styleVal.ToString());
        }
开发者ID:StevePotter,项目名称:Tableize,代码行数:75,代码来源:Tableizer.cs

示例11: RemoveOverlappingSpanInParagraph

		void RemoveOverlappingSpanInParagraph(HtmlNode parent) {
			if (0 != string.Compare(parent.Name, "p", StringComparison.InvariantCultureIgnoreCase)) { return; }

			if (parent.ChildNodes.Count != 1) {
				return;
			}

			var child = parent.ChildNodes[0];
			if (0 != string.Compare(child.Name, "span", StringComparison.InvariantCultureIgnoreCase)) { return; }

			if (child.Attributes.Count > 1) { return; }

			var attr0 = child.Attributes[0];
			if (0 != string.Compare(attr0.Name, "style", StringComparison.InvariantCultureIgnoreCase)){ return; }

			var parentStyle = ParseStyle(parent);
			var spanStyle = ParseStyle(attr0.Value);
			foreach (var kp in spanStyle) {
				parentStyle[kp.Key] = kp.Value;
			}

			var finalStyle = ComposeStyle(parentStyle);
			parent.SetAttributeValue("style", finalStyle);
			parent.InnerHtml = child.InnerHtml;
		}
开发者ID:cleannote,项目名称:cleannote-csharp,代码行数:25,代码来源:Converter.cs

示例12: ApplyOutlineCssToHtmlNode

        private static void ApplyOutlineCssToHtmlNode(HtmlNode node, Dictionary<string, string> outlineStyle)
        {
            string inlineStyle = node.GetAttributeValue("style", String.Empty);
            Dictionary<string, string> inlineStyleAsDictionary = ConvertStyleToDictionary(inlineStyle);

            AddOutlineStylesToInlineStyles(inlineStyleAsDictionary, outlineStyle);

            string mergedCss = string.Join(";", inlineStyleAsDictionary.Select(x => string.Format("{0}:{1}", x.Key, x.Value)).ToArray());

            node.SetAttributeValue("style", mergedCss);
        }
开发者ID:Jonne,项目名称:CssFlattener,代码行数:11,代码来源:CssFlattener.cs

示例13: HandleObjects

        public override string HandleObjects(HtmlNode node)
        {
            if (node != null)
            {
                // shrink window to 75% of page; 50% if in quotes
                node.SetAttributeValue("width", isInQuoteBlock ? "160" : "240");
                node.SetAttributeValue("height", isInQuoteBlock ? "120" : "180");
            }

            return node.OuterHtml;
        }
开发者ID:bootlegrobot,项目名称:awful2,代码行数:11,代码来源:PostContentStyler.cs

示例14: SetLinkCssClass

        private void SetLinkCssClass(HtmlNode wikiLink)
        {
            var href = wikiLink.GetAttributeValue("href", null) ?? string.Empty;

            int hashIndex = href.IndexOf('#');
            href = (hashIndex >= 0) ? href.Substring(0, hashIndex) : href;

            string linkArticle = (string.IsNullOrWhiteSpace(href) || href == this.wikiSlashUrlPrefix)
                                     ? WikiDownConfig.WikiIndexArticleSlug
                                     : this.wikiLinkPrefixRemoveRegex.Replace(href, string.Empty).TrimEnd('/');

            var articleSlugExists = this.articleExistsHelper.GetExists(linkArticle);
            if (!articleSlugExists)
            {
                wikiLink.SetAttributeValue("class", ArticleExistsHelper.NoArticleCssClass);
            }
        }
开发者ID:sebnilsson,项目名称:WikiDown,代码行数:17,代码来源:WikiDownArticleHtmlString.cs

示例15: UpdateSingleHref

 private static void UpdateSingleHref(HtmlNode node, string attributeName, string filePath)
 {
     var href = node.GetAttributeValue(attributeName, string.Empty);
     if (PathUtility.IsRelativePath(href))
         node.SetAttributeValue(attributeName, RebaseHref(href, filePath, string.Empty));
 }
开发者ID:yodamaster,项目名称:docfx,代码行数:6,代码来源:DocfxFlavoredIncHelper.cs


注:本文中的HtmlAgilityPack.HtmlNode.SetAttributeValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。