本文整理汇总了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;
}
示例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 };
}
示例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);
}
}
示例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);
}
示例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());
}
}
示例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;
}
示例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();
}
示例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);
}
}
示例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);
}
}
}
}
}
示例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());
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}
}
示例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));
}