本文整理汇总了C#中HtmlAgilityPack.HtmlDocument.Save方法的典型用法代码示例。如果您正苦于以下问题:C# HtmlDocument.Save方法的具体用法?C# HtmlDocument.Save怎么用?C# HtmlDocument.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HtmlAgilityPack.HtmlDocument
的用法示例。
在下文中一共展示了HtmlDocument.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateHtmlFile
public void CreateHtmlFile(ConcurrentDictionary<string, string> localFileChanges, HtmlDocument vehicleWikiPage, string vehicleName, string fileName, string filePath)
{
LocalWikiFileTypeEnum fileType = LocalWikiFileTypeEnum.HTML;
string fileExtension = fileType.ToString();
if (!File.Exists(filePath))
{
// Add new item
vehicleWikiPage.Save($"{filePath}", Encoding.UTF8);
_filePerVehicleLogger.RecordAddFileToLocalWiki(localFileChanges, vehicleName, fileName, fileExtension);
}
else
{
string existingFileText = File.ReadAllText(filePath);
//Create a fake document so we can use helper methods to traverse through the existing file as an HTML document
HtmlDocument htmlDoc = new HtmlDocument();
HtmlNode existingHtml = HtmlNode.CreateNode(existingFileText);
htmlDoc.DocumentNode.AppendChild(existingHtml);
// Get out the last modified times for comparison
var newLastModSection = vehicleWikiPage.DocumentNode.Descendants().SingleOrDefault(x => x.Id == ConfigurationManager.AppSettings["LastModifiedSectionId"]);
var oldLastModSection = existingHtml.OwnerDocument.DocumentNode.Descendants().SingleOrDefault(x => x.Id == ConfigurationManager.AppSettings["LastModifiedSectionId"]);
// If both files have a last modified time
if (newLastModSection != null && oldLastModSection != null)
{
// Update the existing one if the times are different
if (!_filePerVehicleLogger.AreLastModifiedTimesTheSame(oldLastModSection.InnerHtml, newLastModSection.InnerHtml))
{
// Update existing item
vehicleWikiPage.Save($"{filePath}", Encoding.UTF8);
_filePerVehicleLogger.RecordUpdateFileInLocalWiki(localFileChanges, vehicleName, fileName, fileExtension);
}
}
// Add the item if the existing one has no last modified time
else if (oldLastModSection == null)
{
// Update existing item
vehicleWikiPage.Save($"{filePath}", Encoding.UTF8);
_filePerVehicleLogger.RecordUpdateFileInLocalWiki(localFileChanges, vehicleName, fileName, fileExtension);
}
else
{
string noLastModifiedSectionExceptionMessage = $"Unable to find the '{ConfigurationManager.AppSettings["LastModifiedSectionId"]}' section, information comparision failed.";
_consoleManager.WriteException(noLastModifiedSectionExceptionMessage);
throw new InvalidOperationException(noLastModifiedSectionExceptionMessage);
}
}
}
示例2: ToHtml
private static string ToHtml(HtmlDocument document) {
var sb = new StringBuilder();
using (var writer = new StringWriter(sb)) {
document.Save(writer);
return sb.ToString();
}
}
示例3: SaveFile
protected override void SaveFile(string content)
{
var html = new HtmlDocument();
Console.WriteLine("Le header de la requete pour le site " + Uri + " est : ");
Console.WriteLine(Header+"\n");
html.LoadHtml(content);
html.Save("page.html");
foreach (var imageUrl in GetAllImageUrl(html))
{
Console.WriteLine("Download de l'image {0}",imageUrl);
Uri url;
if (imageUrl.StartsWith("http"))
{
url = new Uri(imageUrl);
}
else
{
if (imageUrl.StartsWith("//"))
url = new Uri("http:"+imageUrl);
else
url = new Uri("http://" + Uri.Host + imageUrl);
}
var image = new ImageFromInternet(url);
image.Download();
}
}
示例4: Main
static void Main (string [] args)
{
HtmlDocument doc = new HtmlDocument();
doc.Load(args [0]);
doc.OptionOutputAsXml = true;
doc.Save(args [1]);
}
示例5: Flatten
public string Flatten(string originalHtml, string css)
{
if (originalHtml == null)
{
throw new ArgumentNullException("originalHtml");
}
if (css == null)
{
throw new ArgumentNullException("css");
}
Log.Debug("Reading css stule rules from css");
IEnumerable<StyleRule> styleRules = GetStyleRules(css);
Log.DebugFormat("Found {0} style rules", styleRules.Count());
Log.Debug("Parsing Html document");
var document = new HtmlDocument();
document.LoadHtml(originalHtml);
Log.Debug("Applying style rules to html elements");
ApplyOutlineCssToDocument(document, styleRules);
var sw = new StringWriter();
document.Save(sw);
return sw.ToString();
}
示例6: DoTranslation
public static int DoTranslation(string htmlfilename, string fromlanguage, string tolanguage)
{
string htmldocument = File.ReadAllText(htmlfilename);
string htmlout = string.Empty;
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmldocument);
htmlDoc.DocumentNode.SetAttributeValue("lang", TranslationServices.Core.TranslationServiceFacade.LanguageNameToLanguageCode(tolanguage));
var title = htmlDoc.DocumentNode.SelectSingleNode("//head//title");
title.InnerHtml = TranslationServices.Core.TranslationServiceFacade.TranslateString(title.InnerHtml, fromlanguage, tolanguage, "text/html");
var body = htmlDoc.DocumentNode.SelectSingleNode("//body");
if (body.InnerHtml.Length < 10000)
{
body.InnerHtml = TranslationServices.Core.TranslationServiceFacade.TranslateString(body.InnerHtml, fromlanguage, tolanguage, "text/html");
}
else
{
List<HtmlNode> nodes = new List<HtmlNode>();
AddNodes(body.FirstChild, ref nodes);
Parallel.ForEach(nodes, (node) =>
{
if (node.InnerHtml.Length > 10000)
{
throw new Exception("Child node with a length of more than 10000 characters encountered.");
}
node.InnerHtml = TranslationServices.Core.TranslationServiceFacade.TranslateString(node.InnerHtml, fromlanguage, tolanguage, "text/html");
});
}
htmlDoc.Save(htmlfilename, Encoding.UTF8);
return 1;
}
示例7: HtmlErrors_Fix_Test
public void HtmlErrors_Fix_Test()
{
#region Auto close mallformed paragraphs
var outputWriter = new StringWriter();
var doc = new HtmlDocument();
string output;
doc.LoadHtml("<div class=\"wrapper\"><p><strong>This paragraph <br>is not closed</strong></div>");
doc.OptionWriteEmptyNodes = true;
doc.Save(outputWriter);
output = outputWriter.ToString();
Assert.IsTrue(output.Contains("<p />"));
#endregion
#region Include childs in mallformed lists
outputWriter = new StringWriter();
doc = new HtmlDocument();
doc.LoadHtml("<div class=\"wrapper\"><ul><li>Item of the list</li></div>");
doc.OptionWriteEmptyNodes = true;
doc.Save(outputWriter);
output = outputWriter.ToString();
Assert.IsTrue(output.Contains("</ul>"));
#endregion
#region Upper case elements
outputWriter = new StringWriter();
doc = new HtmlDocument();
doc.LoadHtml("<div class=\"wrapper\"><UL><li>Item of the list</li></div>");
doc.OptionWriteEmptyNodes = true;
doc.Save(outputWriter);
output = outputWriter.ToString();
Assert.IsTrue(output.Contains("<ul>"));
#endregion
}
示例8: ProcessContent
public string ProcessContent(string text, string flavor) {
var wc = _wca.GetContext();
var baseUrl = wc.CurrentSite.BaseUrl;
if (string.IsNullOrWhiteSpace(baseUrl)) return text;
var baseUri = new Uri(baseUrl);
var doc = new HtmlDocument();
doc.LoadHtml(text);
var links = doc.DocumentNode.SelectNodes("//a[@href]");
if (links != null) {
foreach (var link in links) {
MakeAbsolute(link.Attributes["href"], baseUri);
}
}
var imgs = doc.DocumentNode.SelectNodes("//img[@src]");
if (imgs != null) {
foreach (var img in imgs) {
MakeAbsolute(img.Attributes["src"], baseUri);
}
}
var sb = new StringBuilder();
using (var writer = new StringWriter(sb)) {
doc.Save(writer);
return sb.ToString();
}
}
示例9: HtmlSummary
/// <summary>
/// Create a new empty Html Summary from an HTTP response
/// </summary>
/// <param name="statusCode">Response Status Code</param>
/// <param name="url">Request Url</param>
/// <param name="body">Response body</param>
/// <param name="mediaType">Response content media type header value</param>
public HtmlSummary(HttpStatusCode statusCode, string url, string body, string mediaType)
: this()
{
this.StatusCode = statusCode;
this.Url = url;
if (((int)statusCode)/100 != 2)
{
this.FailureReason = string.Format(@"Remote Server returned status code {0} {1}",
(int) statusCode, statusCode);
return;
}
if (mediaType.IsNullOrWhiteSpace() ||
!HtmlMediaTypes.Any(_ => _.Equals(mediaType, StringComparison.OrdinalIgnoreCase)))
{
this.FailureReason = string.Format
(@"The server at URL {0} returned non-HTML media type '{1}'", this.Url, mediaType);
return;
}
var doc = new HtmlDocument {OptionFixNestedTags = true};
doc.LoadHtml(body);
CountFrequency(doc.DocumentNode, this.Frequency);
using (var writer = new StringWriter())
{
doc.Save(writer);
this.Body = writer.GetStringBuilder().ToString();
}
}
示例10: 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);
}
示例11: ProcessTableOfContents
/// <summary>
/// Takes HTML and parses out all heading and sets IDs for each heading. Then sets the Headings property on the page.
/// </summary>
private string ProcessTableOfContents(string content) {
var doc = new HtmlDocument();
doc.OptionUseIdAttribute = true;
doc.LoadHtml(content);
var allNodes = doc.DocumentNode.DescendantNodes();
var allHeadingNodes = allNodes.Where(node =>
node.Name.Length == 2
&& node.Name.StartsWith("h", System.StringComparison.InvariantCultureIgnoreCase)
&& !node.Name.Equals("hr", StringComparison.InvariantCultureIgnoreCase)).ToList();
var headings = new List<Heading>();
foreach (var heading in allHeadingNodes) {
var id = heading.InnerHtml.Replace(" ", "_");
id = HttpUtility.HtmlAttributeEncode(HttpUtility.UrlEncode(id)); // TODO: What encoding should happen here?
heading.SetAttributeValue("id", id);
headings.Add(new Heading(id, Convert.ToInt32(heading.Name.Remove(0, 1)), heading.InnerText));
}
Page.Headings = headings;
var docteredHTML = new StringWriter();
doc.Save(docteredHTML);
return docteredHTML.ToString();
}
示例12: ParseDirectoryBrowsingHTML
public string ParseDirectoryBrowsingHTML(string path, string[] dirs, string[] files)
{
var doc = new HtmlDocument();
doc.Load(path);
HtmlNode fileList = doc.DocumentNode.SelectSingleNode("//ul[@id='list']");
StringBuilder listHTML = new StringBuilder();
string listItemFormat = "<li>{0} <a href='{1}'>{2}</a></li>";
foreach (string dir in dirs)
{
listHTML.Append(String.Format(listItemFormat, "D >", dir+"/", dir));
}
foreach (string file in files)
{
listHTML.Append(String.Format(listItemFormat, "F >", file, file));
}
fileList.InnerHtml = listHTML.ToString();
string result = null;
using (StringWriter writer = new StringWriter())
{
doc.Save(writer);
result = writer.ToString();
writer.Flush();
}
return result;
}
示例13: Main
static void Main(string[] args)
{
string p = "C:\\Users\\Victor\\AppData\\Local\\Temp\\index.htm";
var doc = new HtmlDocument();
doc.Load(p);
ProcessURIs.Go(doc.DocumentNode, new Uri(p));
doc.Save(p + "1.htm", doc.StreamEncoding);
}
示例14: addToDiskCache
/// <summary>
/// gets the XElement from the data.xml file by page name and item name
/// </summary>
/// <param name="pageName"></param>
/// <param name="itemName"></param>
/// <returns></returns>
//public static XElement GetAcordingXElementToNameTag(string pageName, string itemName)
//{
// try
// {
// return DataIO.LoadData.Element("root").Elements("page").Where(t => t.Attribute("name").Value.ToLower().Equals(pageName)).Single().Elements("item").Where(s => s.Attribute("id").Value.ToLower().Equals(itemName.ToLower())).Single();
// }
// catch // if the element doesn't exist, return null
// {
// return null;
// }
//}
public static void addToDiskCache(HtmlDocument doc, string pageName)
{
// check if the cache directory exists and create it if necessary
DirectoryInfo pageCacheDir = new DirectoryInfo(DataIO.CacheDirectory);
if (!pageCacheDir.Exists)
pageCacheDir.Create();
// write the new file to disk and add it to the cache
doc.Save(DataIO.CacheDirectory + "html_document_" + pageName + ".htm");
}
示例15: Clean
internal static string Clean(string raw)
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(raw);
using (var fixedHtmlStream = new MemoryStream())
{
htmlDoc.Save(fixedHtmlStream);
return ConvertToString(fixedHtmlStream);
}
}