本文整理汇总了C#中HtmlAgilityPack.HtmlDocument.CreateElement方法的典型用法代码示例。如果您正苦于以下问题:C# HtmlDocument.CreateElement方法的具体用法?C# HtmlDocument.CreateElement怎么用?C# HtmlDocument.CreateElement使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HtmlAgilityPack.HtmlDocument
的用法示例。
在下文中一共展示了HtmlDocument.CreateElement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DecodeHtml
/// <summary>
/// Decodes the HTML.
/// </summary>
/// <param name="htmlText">The html text.</param>
/// <returns>String without any html tags.</returns>
public static string DecodeHtml(string htmlText)
{
htmlText = htmlText.Replace("<p>", "").Replace("</p>", "\r\n\r\n");
string decoded = String.Empty;
if (htmlText.IndexOf('<') > -1 || htmlText.IndexOf('>') > -1 || htmlText.IndexOf('&') > -1)
{
try
{
HtmlDocument document = new HtmlDocument();
var decode = document.CreateElement("div");
htmlText = htmlText.Replace(".<", ". <").Replace("?<", "? <").Replace("!<", "! <").Replace("'", "'");
decode.InnerHtml = htmlText;
decoded = WebUtility.HtmlDecode(decode.InnerText);
decoded = Regex.Replace(decoded, "<!--.*?-->", string.Empty, RegexOptions.Singleline);
}
catch { }
}
else
{
decoded = htmlText;
}
return decoded;
}
示例2: GetExternalReferencesListNode
private static HtmlNode GetExternalReferencesListNode(
HtmlDocument document,
IEnumerable<ExternalReference> externalReferences)
{
var list = document.CreateElement("ol");
foreach (var reference in externalReferences)
{
var item = document.CreateElement("li");
string referenceId = GetExternalReferenceId(reference.Index);
var backLink = document.CreateElement("a");
backLink.InnerHtml = "<strong>^</strong>";
backLink.SetAttributeValue("href", "#" + referenceId + BackLinkReferenceIdSuffix);
var externalLink = document.CreateElement("a");
externalLink.InnerHtml = reference.Url;
externalLink.SetAttributeValue("href", reference.Url);
externalLink.SetAttributeValue("name", referenceId);
item.AppendChild(backLink);
item.AppendChild(document.CreateTextNode(" "));
item.AppendChild(externalLink);
list.AppendChild(item);
}
return list;
}
示例3: DecodeHtml
public static string DecodeHtml(string htmltext)
{
htmltext = htmltext.Replace("<p>", "").Replace("</p>", "\r\n\r\n");
string decoded = String.Empty;
if (htmltext.IndexOf('<') > -1 || htmltext.IndexOf('>') > -1 || htmltext.IndexOf('&') > -1)
{
try
{
HtmlDocument document = new HtmlDocument();
var decode = document.CreateElement("div");
htmltext = htmltext.Replace(".<", ". <").Replace("?<", "? <").Replace("!<", "! <").Replace("'", "'");
decode.InnerHtml = htmltext;
var allElements = decode.Descendants().ToArray();
for (int n = allElements.Length - 1; n >= 0; n--)
{
if (allElements[n].NodeType == HtmlNodeType.Comment || allElements[n].Name.EqualNoCase("style") || allElements[n].Name.EqualNoCase("script"))
{
allElements[n].Remove();
}
}
decoded = WebUtility.HtmlDecode(decode.InnerText);
}
catch { }
}
else
{
decoded = htmltext;
}
return decoded;
}
示例4: Parse
public void Parse(string input, string[] args = null)
{
var xxr = new XamlXmlReader(new StringReader(input), new XamlSchemaContext());
var graphReader = new XamlObjectWriter(xxr.SchemaContext);
while (xxr.Read())
graphReader.WriteNode(xxr);
var page = (Page)graphReader.Result;
// Map our generators
var g = new Generator();
g.Map<Page, PageGeneratorBlock>();
g.Map<Button, ButtonGeneratorBlock>();
g.Map<StackPanel, StackPanelGeneratorBlock>();
var doc = new HtmlDocument();
var html = doc.CreateElement("html");
g.Generate(html, page);
// HTML5 Doc type
doc.DocumentNode.AppendChild(doc.CreateComment("<!DOCTYPE html>"));
doc.DocumentNode.AppendChild(html);
doc.Save("test.htm");
var cssContents = g.GenerateStyles(page);
File.WriteAllText("XamlCore.css", cssContents);
}
示例5: WriteContent
private void WriteContent(HtmlDocument doc)
{
HtmlNode bodyContent = doc.GetElementbyId("bodyContent");
var heading = doc.CreateElement("h1");
heading.InnerHtml = "Heading";
bodyContent.AppendChild(heading);
HtmlNode table = bodyContent.CreateElement("table");
table.CreateAttributeWithValue("class", "table table-striped table-bordered");
var tableHead = table.CreateElement("thead");
var headerRow = tableHead.CreateElement("tr");
headerRow.CreateElementWithHtml("td", "First");
headerRow.CreateElementWithHtml("td", "Second");
headerRow.CreateElementWithHtml("td", "Third");
headerRow.CreateElementWithHtml("td", "Fourth");
headerRow.CreateElementWithHtml("td", "Fifth");
HtmlNode tableBody = table.CreateElement("tbody");
const string text = "Fi fa fo fum fi fa fo fum fi fa fo fum fi fa fo fum";
for (int i = 0; i < 10; i++)
{
HtmlNode bodyRow = tableBody.CreateElement("tr");
bodyRow.CreateElementWithHtml("td", i + " first " + text);
bodyRow.CreateElementWithHtml("td", i + " second " + text);
bodyRow.CreateElementWithHtml("td", i + " third " + text);
bodyRow.CreateElementWithHtml("td", i + " fourth " + text);
bodyRow.CreateElementWithHtml("td", i + " fifth " + text);
}
}
示例6: GrabArticle
static Article GrabArticle(HtmlDocument doc)
{
Article article = new Article();
HtmlNode articleContent = doc.CreateElement("div");
ParagraphParentCollection paragraphParents = new ParagraphParentCollection(new ParagraphCollection(doc.DocumentNode.SelectNodes("//p")));
// Replace br tags with paragraph tags.
doc.DocumentNode.InnerHtml = Regex.Replace(doc.DocumentNode.InnerHtml, @"<br/?>[ \r\n\s]*<br/?>", @"</p><p>");
// TODO handle title.
article.Title = doc.DocumentNode.SelectSingleNode("//title") == null ? null : doc.DocumentNode.SelectSingleNode("//title").InnerText;
foreach (ParagraphParent parent in paragraphParents)
{
foreach (HtmlAttribute att in parent.Node.Attributes.AttributesWithName("class"))
{
if (Regex.IsMatch(att.Name, @"/(comment|meta|footer|footnote)/"))
parent.Score -= 50;
else if (Regex.IsMatch(att.Name, @"/((^|\\s)(post|hentry|entry[-]?(content|text|body)?|article[-]?(content|text|body)?)(\\s|$))/"))
parent.Score += 25;
break;
}
foreach (HtmlAttribute att in parent.Node.Attributes.AttributesWithName("id"))
{
if (Regex.IsMatch(att.Name, @"/(comment|meta|footer|footnote)/"))
parent.Score -= 50;
else if (Regex.IsMatch(att.Name, @"/^(post|hentry|entry[-]?(content|text|body)?|article[-]?(content|text|body)?)$/"))
parent.Score += 25;
}
foreach (Paragraph paragraph in parent.Paragraphs)
{
if (paragraph.Node.InnerText.Length > 10)
parent.Score++;
parent.Score += GetCharCount(paragraph.Node);
}
}
ParagraphParent winner = paragraphParents.OrderByDescending(a => a.Score).FirstOrDefault();
// TODO cleanup.
winner.Clean("style");
winner.KillDivs();
winner.KillBreaks();
winner.Clean("form");
winner.Clean("object");
winner.Clean("table", 250);
winner.Clean("h1");
winner.Clean("h2");
winner.Clean("iframe");
winner.Clean("script");
article.Content.DocumentNode.AppendChild(winner.Node);
return article;
}
示例7: when_html_document_doesnt_contain_rss_feed
public void when_html_document_doesnt_contain_rss_feed()
{
var document = new HtmlDocument();
document.CreateElement("html");
var parser = new Scraper(document);
var actual = parser.GetRssFeedUrl();
Assert.IsNull(actual);
}
示例8: Execute
public override void Execute(IEmailItem emailItem = null, int? lastExitCode = null)
{
if (AppliesTo(emailItem, lastExitCode))
{
if (BodyFormat.Text == emailItem.Message.Body.BodyFormat)
{
StringBuilder sb = new StringBuilder();
sb.Append(emailItem.Message.GetBody());
sb.AppendLine();
sb.AppendLine();
sb.Append(Text);
emailItem.Message.SetBody(sb.ToString());
}
if (BodyFormat.Rtf == emailItem.Message.Body.BodyFormat)
{
var messageRtf = new RtfDocument(emailItem.Message.GetBody());
var mergeRtf = new RtfDocument(Rtf);
if (messageRtf.Merge(mergeRtf))
{
emailItem.Message.SetBody(messageRtf.Content);
}
}
if (BodyFormat.Html == emailItem.Message.Body.BodyFormat)
{
var messageDoc = new HtmlDocument();
messageDoc.LoadHtml(emailItem.Message.GetBody());
var disclaimerDoc = new HtmlDocument();
disclaimerDoc.LoadHtml(Html);
var messageBodyNode = messageDoc.DocumentNode.SelectSingleNode("//body");
var disclaimerBodyNode = disclaimerDoc.DocumentNode.SelectSingleNode("//body");
var brNode = messageDoc.CreateElement("br");
messageBodyNode.AppendChild(brNode);
messageBodyNode.AppendChildren(disclaimerBodyNode.ChildNodes);
emailItem.Message.SetBody(messageDoc.DocumentNode.InnerHtml);
}
if (null != Handlers && Handlers.Count > 0)
{
foreach (IHandler handler in Handlers)
{
handler.Execute(emailItem, lastExitCode);
}
}
}
}
示例9: TransformImgToPicture
public string TransformImgToPicture(string content)
{
try
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(content);
// - activating"do no harm"-mode
doc.OptionFixNestedTags = false;
doc.OptionAutoCloseOnEnd = false;
doc.OptionCheckSyntax = false;
HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//img[@src]");
if (collection == null)
return content;
var changed = false;
foreach (HtmlNode img in collection)
{
HtmlAttribute src = img.Attributes["src"];
HtmlAttribute cls = img.Attributes["class"];
if ((src != null && src.Value.IndexOf("slimmage=true", StringComparison.OrdinalIgnoreCase) > -1)
|| (cls != null && cls.Value.IndexOf("slimmage", StringComparison.OrdinalIgnoreCase) > -1))
{
// - append fallback image
HtmlNode container = doc.CreateElement("noscript");
container.SetAttributeValue("data-slimmage", "true");
//copy attributes for IE6/7/8 support
foreach (var a in img.Attributes)
{
container.SetAttributeValue("data-img-" + a.Name, a.Value);
}
//Place 'img' inside 'noscript'
img.ParentNode.InsertBefore(container, img);
img.Remove();
container.AppendChild(img);
changed = true;
}
}
//Don't modify the DOM unless you actually edited the HTML
return changed ? doc.DocumentNode.OuterHtml : content;
}
catch(Exception ex)
{
Trace.TraceWarning("SlimResponse failed to parse HTML: " + ex.ToString() + ex.StackTrace);
// - better that nothing(tm) ...
//return content;
return ex.ToString();
}
}
示例10: ReplaceDeletedImageBySpanCoupons
public string ReplaceDeletedImageBySpanCoupons(string htmlContent)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlContent);
foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//img[@class='" + hdnImageClass.Value + "']"))
{
string value = img.Attributes.Contains("value") ? img.Attributes["value"].Value : " ";
HtmlNode lbl = doc.CreateElement("span");
lbl.Attributes.Add("class", hdnImageClass.Value);
lbl.InnerHtml = value;
img.ParentNode.ReplaceChild(lbl, img);
}
return doc.DocumentNode.OuterHtml;
}
示例11: ReplaceDeletedIframeBySpan
public string ReplaceDeletedIframeBySpan(string htmlContent)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlContent);
foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//iframe"))
{
HtmlNode lbl = doc.CreateElement("span");
lbl.Attributes.Add("class", "IF");
lbl.Attributes.Add("height", "187");
lbl.Attributes.Add("width", "240");
img.ParentNode.ReplaceChild(lbl, img);
}
return doc.DocumentNode.OuterHtml;
}
示例12: Execute
public override TaskExecutionDetails Execute(string Value)
{
TaskExecutionDetails d = new TaskExecutionDetails();
HtmlDocument doc = new HtmlDocument();
doc.Load(IO.IOHelper.MapPath(SystemDirectories.Masterpages) + "/" + TargetFile);
//if (doc.DocumentNode.SelectSingleNode(string.Format("//link [@href = '{0}']", Value)) == null)
//{
HtmlNode target = doc.DocumentNode.SelectSingleNode(string.IsNullOrEmpty(TargetSelector) ? "//head" : TargetSelector.ToLower());
if (target != null)
{
HtmlNode s = doc.CreateElement("link");
//s.Name = "link";
s.Attributes.Append("rel", "stylesheet");
s.Attributes.Append("type", "text/css");
s.Attributes.Append("href", Value);
if (!string.IsNullOrEmpty(Media))
s.Attributes.Append("media", Media);
target.AppendChild(s);
doc.Save(IO.IOHelper.MapPath(SystemDirectories.Masterpages) + "/" + TargetFile);
d.TaskExecutionStatus = TaskExecutionStatus.Completed;
d.NewValue = Value;
}
else
d.TaskExecutionStatus = TaskExecutionStatus.Cancelled;
//}
//else
// d.TaskExecutionStatus = TaskExecutionStatus.Cancelled;
return d;
}
示例13: GetPreview
public static string GetPreview(string html, string replacmentHtml, Guid productID)
{
var doc = new HtmlDocument();
doc.LoadHtml(string.Format("<html>{0}</html>", htmlTags.Replace(html, string.Empty)));
var nodes = doc.DocumentNode.SelectNodes("//div[translate(@class,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='asccut']");
if (nodes != null)
{
foreach (var node in nodes)
{
var newNode = doc.CreateElement("div");
var styleAttr = doc.CreateAttribute("style");
styleAttr.Value = "display:inline;";
newNode.Attributes.Append(styleAttr);
newNode.InnerHtml = replacmentHtml ?? string.Empty;
node.ParentNode.ReplaceChild(newNode, node);
}
}
ProcessCustomTags(doc, productID);
return htmlTags.Replace(doc.DocumentNode.InnerHtml, string.Empty);
}
示例14: CreateNode
public static HtmlNode CreateNode(
HtmlDocument document,
string name,
string className = null,
HtmlNode parentNode = null)
{
var node = document.CreateElement(name);
if (!string.IsNullOrWhiteSpace(className))
{
node.SetAttributeValue("class", className);
}
if (parentNode != null)
{
parentNode.AppendChild(node);
}
return node;
}
示例15: Download
public void Download(HtmlDocument document, string path)
{
Directory.CreateDirectory(ResourcePath);
//Descargar todos los recursos
_downloadImages(document);
_downloadResources(document, "link", "href", true);
_downloadResources(document, "script", "src");
//Añadir cabeceras meta para indificar codificación UTF8
HtmlNode meta = document.CreateElement("meta");
meta.Attributes.Add("charset", "utf-8");
document.DocumentNode.SelectSingleNode("//head").ChildNodes.Add(meta);
/*HtmlNode meta2 = document.CreateElement("meta");
meta2.Attributes.Add("http-equiv", "Content-Type");
meta2.Attributes.Add("content", "Type=text/html; charset=utf-8");
document.DocumentNode.SelectSingleNode("//head").ChildNodes.Add(meta2);*/
File.WriteAllText(path, document.DocumentNode.WriteTo(), new UTF8Encoding(true));
}