miglior modo per trovare fine del tag body in html
Domanda
Sto scrivendo un programma per aggiungere del codice in file HTML
Stavo per usare una serie di indexOf e loop di trovare ciò che è essenzialmente "" X (Dove X è il posto im cercando)
Mi venne in mente che ci potrebbe essere un modo più eloquente di fare questo
Qualcuno ha qualche suggerimento.
come si presenta attualmente
<body onLoad="JavaScript:top.document.title='Abraham L Barbrow'; if (self == parent) document.getElementById('divFrameset').style.display='block';">
quello che dovrebbe essere simile quando im fatto
<body onLoad="JavaScript:top.document.title='Abraham L Barbrow'; if (self == parent) document.getElementById('divFrameset').style.display='block';">
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-9xxxxxx-1");
pageTracker._trackPageview();
} catch(err) {}</script>
Soluzione
Non sono sicuro che ti sto comprensione, ma vuoi dire questo?
// Given an HTML document in "htmlDocument", and new content in "newContent"
string newHtmlDocument = htmlDocument.Replace("</body>", newContent+"</body>");
E probabilmente è ovvio non so c # ... Si sarebbe probabilmente vuole fare il caso tag "corpo" insensibile tramite espressioni regolari.
Altri suggerimenti
mi sento di raccomandare di utilizzare HtmlAgilityPack per analizzare il codice HTML in DOM e lavorare con esso.
public string AddImageLink(string emailBody,string imagePath)
{
try
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(emailBody);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//body");
// get body using xpath query ("//body")
// create the new node ..
HtmlNodeCollection LinkNode = new HtmlNodeCollection(node);
//
HtmlNode linkNode = new HtmlNode(HtmlNodeType.Element,doc,0);
linkNode.Name = "A";
linkNode.Attributes.Add("href","www.splash-solutions.co.uk");
HtmlNode imgNode = new HtmlNode(HtmlNodeType.Element,doc,1);
imgNode.Name = "img";
imgNode.Attributes.Add("src",imagePath);
//appending the linknode with image node
linkNode.AppendChild(imgNode);
LinkNode.Append(linkNode);
//appending LinkNode to the body of the html
node.AppendChildren(LinkNode);
StringWriter writer = new StringWriter();
doc.Save(writer);
emailBody = writer.ToString();
return emailBody;
}
Se i file HTML sono validato XHTML si può sempre utilizzare la classe XmlDocument per interpretarlo. Si potrebbe quindi facilmente cercare il corpo e aggiungere un elemento secondario ad esso. Ciò porrebbe l'elemento a destra prima del tag di chiusura.
Si potrebbe desiderare di guardare con l'Html Agility pacchetto
Non sono sicuro se il contenuto ad esempio si desidera aggiungere dopo il tag è quella giusta o no, ma se lo è, sto vedendo due problemi:
- Il codice di Google Analytics dovrebbe essere aggiunto appena prima del tag di chiusura , non il tag di apertura. Ciò assicura che non c'è bisogno di aspettare che si carichi prima di caricare il proprio codice.
- Se si aggiunge qualche altra javascript, perché non aggiungere che in un file esterno, ed eseguire quella onload invece?
La speranza che è di qualche aiuto:)
Questo è quello che ho ottenuto
non esitate a dare suggerimenti
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Multiselect = true;
OFD.Filter = "HTML Files (*.htm*)|*.HTM*|" +
"All files (*.*)|*.*";
if (OFD.ShowDialog() == DialogResult.OK)
{
foreach (string s in OFD.FileNames)
{
Console.WriteLine(s);
AddAnalytics(s);
}
MessageBox.Show("done!");
}
}
private void AddAnalytics(string filename)
{
string Htmlcode = "";
using (StreamReader sr = new StreamReader(filename))
{
Htmlcode = sr.ReadToEnd();
}
if (!Htmlcode.Contains(textBox1.Text))
{
Htmlcode = Htmlcode.Replace("</body>", CreateCode(textBox1.Text) + "</body>");
using (StreamWriter sw = new StreamWriter(filename))
{
sw.Write(Htmlcode);
}
}
}
private string CreateCode(string Number)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("<script type=\"text/javascript\">");
sb.AppendLine("var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");");
sb.AppendLine("document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' ");
sb.AppendLine("<//script>");
sb.AppendLine("<script type=/\"text//javascript/\">");
sb.AppendLine("try {");
sb.AppendLine(string.Format("var pageTracker = _gat._getTracker(/\"{0}/\");", Number));///"UA-9909000-1"
sb.AppendLine("pageTracker._trackPageview();");
sb.AppendLine("} catch(err) {}<//script>");
sb.AppendLine();
return sb.ToString();
}
}