本文整理汇总了C#中HtmlAgilityPack.HtmlDocument.Save方法的典型用法代码示例。如果您正苦于以下问题:C# HtmlAgilityPack.HtmlDocument.Save方法的具体用法?C# HtmlAgilityPack.HtmlDocument.Save怎么用?C# HtmlAgilityPack.HtmlDocument.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HtmlAgilityPack.HtmlDocument
的用法示例。
在下文中一共展示了HtmlAgilityPack.HtmlDocument.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Grab
List<Show> Grab(GrabParametersBase p)
{
var shows = new List<Show>();
try
{
var param = (GrabParameters)p;
var wr = WebRequest.Create(string.Format(urlFormat, (int)param.ChannelId));
_logger.WriteEntry(string.Format("Grabbing Channel {0} ...", param.ChannelId), LogType.Info);
var res = (HttpWebResponse)wr.GetResponse();
var doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(res.GetResponseStream());
doc.OptionOutputAsXml = true;
var writer = new StringWriter();
doc.Save(writer);
var xml = XDocument.Load(new StringReader(writer.ToString()));
FillShows(xml, shows);
for (int i = shows.Count - 1; i >= 0; i--)
{
var show = shows[i];
show.Channel = param.ChannelId.ToString();
if (i == shows.Count - 1)
show.EndTime = show.StartTime.AddHours(12);// usually 3-4 days from now , not that important
else
show.EndTime = shows[i + 1].StartTime;
}
}
catch (Exception ex)
{
_logger.WriteEntry(ex.Message, LogType.Error);
}
_logger.WriteEntry(string.Format("Found {0} Shows", shows.Count), LogType.Info);
return shows;
}
示例2: ConvertHSBCHTMLFileToFineAnts
static FineAntsCore.Statement ConvertHSBCHTMLFileToFineAnts(FileInfo fileInfo)
{
HtmlAgilityPack.HtmlDocument brokenDocument = new HtmlAgilityPack.HtmlDocument();
brokenDocument.Load(fileInfo.FullName);
brokenDocument.OptionOutputAsXml = true;
string fixedXmlFileName = fileInfo.FullName + ".fixed.xml";
brokenDocument.Save(fixedXmlFileName);
XmlDocument document = new XmlDocument();
document.Load(fixedXmlFileName);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(document.NameTable);
namespaceManager.AddNamespace("d", "http://www.w3.org/1999/xhtml");
XmlNode closingBalanceNode = document.SelectSingleNode("/span/d:html/d:body/d:div[@id='top']/d:div[@id='innerPage']/d:div[@id='wrapper']/d:div[@id='main']/d:div[@id='content']/d:div[@class='containerMain']/d:div[@class='hsbcMainContent hsbcCol']/d:div[@class='extContentHighlightPib hsbcCol']/d:table/d:tbody/d:tr[last()]/d:td[6]/d:p", namespaceManager);
XmlNode closingBalanceSignNode = document.SelectSingleNode("/span/d:html/d:body/d:div[@id='top']/d:div[@id='innerPage']/d:div[@id='wrapper']/d:div[@id='main']/d:div[@id='content']/d:div[@class='containerMain']/d:div[@class='hsbcMainContent hsbcCol']/d:div[@class='extContentHighlightPib hsbcCol']/d:table/d:tbody/d:tr[last()]/d:td[7]/d:p", namespaceManager);
int closingBalance = moneyInPenceFromString(closingBalanceNode.InnerText.Trim());
if (closingBalanceSignNode.InnerText.Trim() == "D") closingBalance = -closingBalance;
XmlNode endDateNode = document.SelectSingleNode("/span/d:html/d:body/d:div[@id='top']/d:div[@id='innerPage']/d:div[@id='wrapper']/d:div[@id='main']/d:div[@id='content']/d:div[@class='containerMain']/d:div[@class='hsbcMainContent hsbcCol']/d:div[@class='extContentHighlightPib hsbcCol']/d:div[@class='extPibRow hsbcRow']/d:div[@class='hsbcPadding']/d:div[@class='hsbcTextRight']", namespaceManager);
string endDateString = HtmlAgilityPack.HtmlEntity.DeEntitize(endDateNode.InnerText).Trim();
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
DateTime endDate = DateTime.ParseExact(endDateString, "dd MMM yyyy", provider);
XmlNode startDateNode = document.SelectSingleNode("/span/d:html/d:body/d:div[@id='top']/d:div[@id='innerPage']/d:div[@id='wrapper']/d:div[@id='main']/d:div[@id='content']/d:div[@class='containerMain']/d:div[@class='hsbcMainContent hsbcCol']/d:div[@class='extContentHighlightPib hsbcCol']/d:table/d:tbody/d:tr[1]/d:td[1]/d:p", namespaceManager);
string startDateString = HtmlAgilityPack.HtmlEntity.DeEntitize(startDateNode.InnerText).Trim();
DateTime startDate = dateFromDateStringFixedUsingUpperBoundDate(startDateString, endDate.AddDays(-1)).AddDays(1);
List<FineAntsCore.Transaction> transactions = new List<FineAntsCore.Transaction>();
XmlNodeList transactionNodes = document.SelectNodes("/span/d:html/d:body/d:div[@id='top']/d:div[@id='innerPage']/d:div[@id='wrapper']/d:div[@id='main']/d:div[@id='content']/d:div[@class='containerMain']/d:div[@class='hsbcMainContent hsbcCol']/d:div[@class='extContentHighlightPib hsbcCol']/d:table/d:tbody/d:tr[position()>1 and position()<last()]", namespaceManager);
foreach (XmlNode node in transactionNodes)
{
XmlNode dateNode = node.SelectSingleNode("d:td[1]/d:p", namespaceManager);
XmlNode typeNode = node.SelectSingleNode("d:td[2]/d:p", namespaceManager);
XmlNode nameNode = node.SelectSingleNode("d:td[3]/d:p", namespaceManager);
XmlNode moneyOutNode = node.SelectSingleNode("d:td[4]/d:p", namespaceManager);
XmlNode moneyInNode = node.SelectSingleNode("d:td[5]/d:p", namespaceManager);
string date = HtmlAgilityPack.HtmlEntity.DeEntitize(dateNode.InnerText).Trim();
string name = HtmlAgilityPack.HtmlEntity.DeEntitize(getInnerTextIgnoringLinks(nameNode));
string moneyIn = HtmlAgilityPack.HtmlEntity.DeEntitize(moneyInNode.InnerText).Trim();
string moneyOut = HtmlAgilityPack.HtmlEntity.DeEntitize(moneyOutNode.InnerText).Trim();
int money = moneyIn == "" ? -moneyInPenceFromString(moneyOut) : moneyInPenceFromString(moneyIn);
transactions.Add(new FineAntsCore.Transaction(money, dateFromDateStringFixedUsingUpperBoundDate(date, endDate), name, ""));
}
// remove the temporary fixed file
System.IO.File.Delete(fixedXmlFileName);
FineAntsCore.Statement statement = new FineAntsCore.Statement(transactions, startDate, endDate, closingBalance);
return statement;
}
示例3: ExtractFormAndHiddenControls
private void ExtractFormAndHiddenControls (Response response, string formId)
{
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument ();
htmlDoc.LoadHtml (response.Body);
StringBuilder tempxml = new StringBuilder ();
StringWriter tsw = new StringWriter (tempxml);
htmlDoc.OptionOutputAsXml = true;
htmlDoc.Save (tsw);
XmlDocument doc = new XmlDocument ();
doc.LoadXml (tempxml.ToString ());
const string HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
nsmgr.AddNamespace ("html", HTML_NAMESPACE);
#if USE_CORRECT_FORMID
XmlNode formNode = doc.SelectSingleNode ("//html:form[@name='" + formId + "']", nsmgr);
#else
XmlNode formNode = doc.SelectSingleNode ("//html:form", nsmgr);
#endif
if (formNode == null)
throw new ArgumentException ("Form with id='" + formId +
"' was not found in document: " + response.Body);
string actionUrl = formNode.Attributes["action"].Value;
if (actionUrl != null && actionUrl != string.Empty)
base.Url = actionUrl;
XmlNode method = formNode.Attributes["method"];
if (method != null && "POST" == method.Value.ToUpper(CultureInfo.InvariantCulture))
base.IsPost = true;
else
base.IsPost = false;
#if USE_CORRECT_FORMID
foreach (XmlNode inputNode in formNode.SelectNodes ("//html:input", nsmgr))
#else
foreach (XmlNode inputNode in doc.SelectNodes ("//html:input[@type='hidden']", nsmgr))
#endif
{
BaseControl bc = new BaseControl ();
bc.Name = inputNode.Attributes["name"].Value;
if (bc.Name == null || bc.Name == string.Empty)
continue;
if (inputNode.Attributes["value"] != null)
bc.Value = inputNode.Attributes["value"].Value;
else
bc.Value = "";
Controls[bc.Name] = bc;
}
}
示例4: editPost
public void editPost(string postid, string title, string body)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(body);
HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
if (nodes != null)
foreach (HtmlAgilityPack.HtmlNode node in nodes)
{
//获取html源地址
HtmlAgilityPack.HtmlAttribute attr = node.Attributes["src"];
JoeBlogs.MediaObject mediaObj = new JoeBlogs.MediaObject();
mediaObj.Name = "test";
mediaObj.Type = "image/jpeg";
FileStream file = new FileStream(attr.Value, FileMode.Open);
long size = file.Length;
byte[] stream = new byte[size];
file.Read(stream, 0, (int)size);
file.Close();
mediaObj.Bits = stream;
JoeBlogs.MediaObjectInfo mediainfo = metablog.NewMediaObject(mediaObj);
attr.Value = mediainfo.Url;
}
JoeBlogs.Post post = new JoeBlogs.Post();
post.Title = title;
StringWriter writer = new StringWriter();
if (nodes != null)
{
doc.Save(writer);
post.Body = writer.ToString();
}
else
{
post.Body = body;
}
metablog.EditPost(postid, post, true);
}
示例5: ExtractFormAndHiddenControls
string[] ExtractFormAndHiddenControls (Response response)
{
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument ();
htmlDoc.LoadHtml (response.Body);
var tempxml = new StringBuilder ();
var tsw = new StringWriter (tempxml);
htmlDoc.OptionOutputAsXml = true;
htmlDoc.Save (tsw);
var doc = new XmlDocument ();
doc.LoadXml (tempxml.ToString ());
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
nsmgr.AddNamespace ("html", HTML_NAMESPACE);
XmlNode formNode = doc.SelectSingleNode ("//html:form", nsmgr);
if (formNode == null)
throw new ArgumentException ("Form was not found in document: " + response.Body);
string actionUrl = formNode.Attributes ["action"].Value;
XmlNode method = formNode.Attributes ["method"];
var data = new List <string> ();
string name, value;
foreach (XmlNode inputNode in doc.SelectNodes ("//html:input[@type='hidden']", nsmgr)) {
name = inputNode.Attributes["name"].Value;
if (String.IsNullOrEmpty (name))
continue;
XmlAttribute attr = inputNode.Attributes["value"];
if (attr != null)
value = attr.Value;
else
value = String.Empty;
data.Add (name);
data.Add (value);
}
return data.ToArray ();
}
示例6: ProcessHtmlContent
/// <summary>
/// Parse HTML file and find all local contents to download.
/// </summary>
/// <param name="pnum">Problem number</param>
/// <param name="replace">True, if you want to replace old files.</param>
/// <returns>List of files to download</returns>
public static List<DownloadTask> ProcessHtmlContent(long pnum, bool replace)
{
try
{
string external = string.Format("http://uva.onlinejudge.org/external/{0}/", pnum / 100);
string filepath = LocalDirectory.GetProblemHtml(pnum);
if (!File.Exists(filepath)) return new List<DownloadTask>();
List<string> urls = new List<string>();
List<DownloadTask> tasks = new List<DownloadTask>();
HtmlAgilityPack.HtmlDocument htdoc = new HtmlAgilityPack.HtmlDocument();
htdoc.Load(filepath);
GetAllImageFiles(htdoc.DocumentNode, urls);
htdoc.Save(filepath);
foreach (string str in urls)
{
string url = str.StartsWith("./") ? str.Remove(0, 2) : str;
while (url.StartsWith("/")) url = url.Remove(0, 1);
string file = url.Replace('/', Path.DirectorySeparatorChar);
file = LocalDirectory.GetProblemContent(pnum, file);
if (replace || LocalDirectory.GetFileSize(file) < 10)
{
tasks.Add(new DownloadTask(external + url, file, pnum));
}
}
urls.Clear();
return tasks;
}
catch (Exception ex)
{
Logger.Add(ex.Message, "Internet");
return new List<DownloadTask>();
}
}
示例7: Preview_Gen_Click
/// <summary>
/// Generates Image from the specified Website
/// </summary>
protected void Preview_Gen_Click(object sender, EventArgs e)
{
string url = txtUrl.Text;
uri = CreateUri(url);
string domain = uri.Host;
domain = Regex.Replace(domain, @"^(?:http(?:s)?://)?(?:www(?:[0-9]+)?\.)?", string.Empty, RegexOptions.IgnoreCase);
var date = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
var filename = domain + "_" + date + ".html";
/**********************************
* Method WebClient.DownloadString
*
***********************************/
domain = "http://" + domain;
string webpage = GetHTML(url);
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(webpage);
var head = doc.DocumentNode.SelectSingleNode("//head");
var baseTag = HtmlAgilityPack.HtmlNode.CreateNode("<base href=\"" + domain + "\">");
var fontAwesomeRes = HtmlAgilityPack.HtmlNode.CreateNode("<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css\">");
head.PrependChild(baseTag);
head.AppendChild(fontAwesomeRes);
doc = AssignAsbsoluteUri(doc, "//img", "src");
doc = AssignAsbsoluteUri(doc, "//link", "href");
string path = Server.MapPath("Content/Images/Screenshots");
var filepath = path + "\\" + filename;
doc.Save(filepath);//webpageurlNext
iframeLoader.Src = "Content/Images/Screenshots/" + filename;
iframeLoader.Visible = true;
iframeVisible = true;
//StatusText.Text = "Wait until this message disappear";
//ContentLoaded.Visible = true;
}
示例8: TranformHtml
private void TranformHtml(DocumentBuildContext context, string transformed, string relativeModelPath, string outputPath)
{
// Update HREF and XREF
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(transformed);
var srcNodes = html.DocumentNode.SelectNodes("//*/@src");
if (srcNodes != null)
foreach (var link in srcNodes)
{
UpdateSrc(link, context.FileMap, s => UpdateFilePath(s, relativeModelPath));
}
var hrefNodes = html.DocumentNode.SelectNodes("//*/@href");
if (hrefNodes != null)
foreach (var link in hrefNodes)
{
// xref is generated by docfx, and is lower-cased
if (link.Name == "xref")
{
UpdateXref(link, context.XRefSpecMap, context.ExternalXRefSpec, s => UpdateFilePath(s, relativeModelPath), Language);
}
else
{
UpdateHref(link, context.FileMap, s => UpdateFilePath(s, relativeModelPath));
}
}
// Save with extension changed
var subDirectory = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(subDirectory) && !Directory.Exists(subDirectory)) Directory.CreateDirectory(subDirectory);
html.Save(outputPath, Encoding.UTF8);
}
示例9: GetTransactionsFromAccountHistory
public Transaction[] GetTransactionsFromAccountHistory(Stream stream)
{
StreamReader reader = new StreamReader(stream);
// From here: http://stackoverflow.com/questions/12822680/xmldocument-failed-to-load-xhtml-string-because-of-error-reference-to-undeclare
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(reader.ReadToEnd());
doc.OptionOutputAsXml = true;
StringWriter writer = new StringWriter();
doc.Save(writer);
XDocument root = XDocument.Load(new StringReader(writer.ToString()));
XPathNavigator navigator = root.CreateNavigator();
List<Transaction> resultTransactions = new List<Transaction>();
// Pullled from http://stackoverflow.com/questions/2524804/how-do-i-use-xpath-with-a-default-namespace-with-no-prefix
var nameTable = new NameTable();
var nsMgr = new XmlNamespaceManager(nameTable);
nsMgr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
var transactionTable = navigator.SelectSingleNode("span/body/table[1]/tr[4]/td/table[2]");
var transactions = transactionTable.Select("tr");
bool first = true;
foreach (XPathNavigator t in transactions)
{
if (first)
{
first = false;
continue;
}
var cellSelect = t.Select("td");
var cells = new List<string>();
cells.Add(cellSelect.Current.Value.Trim());
while (cellSelect.MoveNext())
{
cells.Add(cellSelect.Current.Value.Trim());
}
if (cells.Count == 8 && (accountsToFilter.Contains(cells[4])))
{
TransactionType tType = TransactionType.Buy;
if (cells[3].Contains("Short-Term Earnings") || cells[3] == "Dividend" || cells[3] == "Earnings")
{
tType = TransactionType.ReinvestDividend;
}
else if (cells[3] == "Contributions")
{
tType = TransactionType.Buy;
}
else if (cells[3] == "ADP/ACP Refunds")
{
tType = TransactionType.Sell;
}
else
{
continue;
}
resultTransactions.Add(new Transaction()
{
FundName = cells[2],
Price = double.Parse(cells[5], System.Globalization.NumberStyles.Any),
Amount = double.Parse(cells[6]),
Total = double.Parse(cells[7], System.Globalization.NumberStyles.Any),
Date = DateTime.Parse(cells[1]),
Type = tType
});
}
}
return resultTransactions.ToArray();
}
示例10: NStartProcessingAuthentification
//---------------------------
public int NStartProcessingAuthentification(int jobID)
{
int status = 0;
//Пишем последнюю страницу в файл
//Создается каталог для контроля считанной странички
/*DirectoryInfo _directoryInfo = new DirectoryInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\OUT");
if (!_directoryInfo.Exists)
{
_directoryInfo.Create();
}*/
HTTPClient client = new HTTPClient(_dbConnectionString, "MySession", _ipProxy, _portProxy, _streamNumber); ;
bool nextPage = true;
string sHTML = "";
string address = "";
string message = "";
HtmlDocument document = new HtmlDocument();
if (!_webAuthentification) // Аунтификация
{
HttpWebResponse httpWebResponse = client.Request(_webPreAuthentificationAddress); //("http://yarsk24.ru");
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.OK)
{
httpWebResponse.Close();
httpWebResponse = client.Request_Post(_webAuthentificationAddress, _webConnectionString); //("http://yarsk24.ru/index/sub/", "user=zero2001&password=2001&rem=1&a=2&ajax=1&rnd=038&_tp_=xml");
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.OK)
{
Stream stream = httpWebResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(stream, this.Encoding)) //System.Text.Encoding.GetEncoding(1251))) / System.Text.Encoding.UTF8
{
sHTML = reader.ReadToEnd();
}
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.OK)
{
httpWebResponse.Close();
_webAuthentification = true;
}
else
{
address = _webAuthentificationAddress;
message = httpWebResponse.StatusCode.ToString();
status = 8;
}
}
else
{
address = _webAuthentificationAddress;
message = httpWebResponse.StatusCode.ToString();
status = 7;
}
}
else
{
address = _webPreAuthentificationAddress;
message = httpWebResponse.StatusCode.ToString();
status = 6;
}
}
if (status != 0)
{
DataDBService ddbs = new DataDBService();
ddbs.WriteErrorMessage(_dbConnectionString, _streamNumber, !string.IsNullOrEmpty(address) ? address : _webAuthentificationAddress, "Ошибка при прохождении аутентификации: " + message);
}
if (_webAuthentification) // Запрос страницы с количеством объявлений
{
HttpWebResponse httpWebResponse = client.Request(_startAddress);
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.OK)
{
Stream stream = httpWebResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(stream, this.Encoding))
{
sHTML = reader.ReadToEnd();
document = new HtmlDocument();
document.LoadHtml(sHTML);
if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.OK)
{
httpWebResponse.Close();
document.Save(_directoryInfo + "\\LastPage" + _streamNumber.ToString() + ".html");
}
else
{
status = 4;
nextPage = false;
}
}
}
else
{
status = 10;
nextPage = false;
}
}
if (_webAuthentification && nextPage) // Цикл по страницам
{
int countPagesTotal = GetPageCount(document, _startAddress);
if (countPagesTotal > 0)
{
//.........这里部分代码省略.........
示例11: TransformHtml
private static void TransformHtml(IDocumentBuildContext context, string html, string relativeModelPath, StreamWriter outputWriter)
{
// Update href and xref
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
var xrefExceptions = TransformHtmlCore(context, relativeModelPath, document);
document.Save(outputWriter);
if (xrefExceptions.Count > 0)
{
throw new AggregateException(xrefExceptions);
}
}
示例12: ParseSaveAndFixImages
private static String ParseSaveAndFixImages(string contents, string dirPath)
{
contents = System.Web.HttpUtility.HtmlDecode(contents);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(new StringReader(contents));
var nav = doc.CreateNavigator();
var strExpression = "//img";
HtmlAgilityPack.HtmlNodeCollection imgTags = doc.DocumentNode.SelectNodes(strExpression);
if (imgTags != null)
{
foreach (HtmlAgilityPack.HtmlNode tag in imgTags)
{
if (tag.Attributes["src"] != null)
{
String imgPath = tag.Attributes["src"].Value;
tag.Attributes["src"].Value = GetAndSaveImage(imgPath, dirPath);
}
}
}
string finalContents = null;
using (StringWriter sw = new StringWriter())
{
doc.Save(sw);
finalContents = sw.ToString();
}
return finalContents;
}
示例13: TranformHtml
private static void TranformHtml(DocumentBuildContext context, string transformed, string relativeModelPath, string outputPath)
{
// Update HREF and XREF
var internalXref = context.XRefSpecMap;
var externalXref = context.ExternalXRefSpec;
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(transformed);
var xrefExceptions = new List<CrossReferenceNotResolvedException>();
var xrefNodes = html.DocumentNode.SelectNodes("//xref/@href");
if (xrefNodes != null)
{
foreach(var xref in xrefNodes)
{
try
{
UpdateXref(xref, internalXref, externalXref, Language);
}
catch (CrossReferenceNotResolvedException e)
{
xrefExceptions.Add(e);
}
}
}
var srcNodes = html.DocumentNode.SelectNodes("//*/@src");
if (srcNodes != null)
foreach (var link in srcNodes)
{
UpdateHref(link, "src", context.FileMap, relativeModelPath);
}
var hrefNodes = html.DocumentNode.SelectNodes("//*/@href");
if (hrefNodes != null)
{
foreach (var link in hrefNodes)
{
UpdateHref(link, "href", context.FileMap, relativeModelPath);
}
}
// Save with extension changed
var subDirectory = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(subDirectory) && !Directory.Exists(subDirectory)) Directory.CreateDirectory(subDirectory);
html.Save(outputPath, Encoding.UTF8);
if (xrefExceptions.Count > 0)
{
throw new AggregateException(xrefExceptions);
}
}
示例14: HtmltoXml
private string HtmltoXml(string html)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
StringBuilder fixedxml = new StringBuilder();
StringWriter sw = new StringWriter(fixedxml);
try
{
StringBuilder tempxml = new StringBuilder();
StringWriter tsw = new StringWriter(tempxml);
doc.OptionOutputAsXml = true;
doc.Save(tsw);
// fix style attribute
// the reason is that style attribute name-value pairs come in different order
// in .NET and GH
// Here I will sort the values of style attribute
XmlDocument tempDoc = new XmlDocument();
tempDoc.LoadXml(tempxml.ToString());
XmlNodeList allNodes = tempDoc.SelectNodes("//*");
foreach (XmlNode n in allNodes)
{
if (n.Attributes["style"] != null)
{
string att = n.Attributes["style"].Value;
string [] style = att.Trim(new char[]{' ', ';'}).Split(';');
for (int styleIndex=0; styleIndex<style.Length; styleIndex++)
{
style[styleIndex] = FixStyleNameValue(style[styleIndex]);
}
Array.Sort(style);
n.Attributes["style"].Value = string.Join(";", style);
}
}
tempDoc.Save(sw);
}
catch (Exception)
{
Console.WriteLine("Error parsing html response...");
Console.WriteLine("Test case aborted");
return "<TestCaseAborted></TestCaseAborted>";
}
return fixedxml.ToString();
}
示例15: Validate
/// <summary>
/// When overridden in a derived class, this validates both the request and response.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void Validate(Object sender, ValidationEventArgs e)
{
_context.Outcome = WebTestOutcome.NotExecuted;
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(((WebTestRequest)e.WebTestItem).HttpResponseBody);
document.OptionOutputAsXml = true;
using (StringWriter writer = new StringWriter())
{
document.Save(writer);
_document = XDocument.Parse(writer.GetStringBuilder().ToString());
}
}