Pergunta

Eu estou escrevendo um programa para adicionar algum código para arquivos de html

Eu ia usar uma série de IndexOf e loops para encontrar o que é, essencialmente, "" X (Onde X é o local im procurando)

Ocorreu-me que poderia haver uma maneira mais eloquente de fazer isso

Alguém tem alguma sugestão.

o que parece atualmente

<body onLoad="JavaScript:top.document.title='Abraham L Barbrow'; if (self == parent) document.getElementById('divFrameset').style.display='block';">

o que deve olhar como quando im feito


<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>
Foi útil?

Solução

Eu não estou certo que eu estou entendendo você, mas que você quer dizer isso?

// Given an HTML document in "htmlDocument", and new content in "newContent"
string newHtmlDocument = htmlDocument.Replace("</body>", newContent+"</body>");

E provavelmente é óbvio que eu não sei c # ... Você provavelmente quer fazer o "corpo" tag caso insensível via regexps.

Outras dicas

Eu recomendaria usar HtmlAgilityPack para analisar o html para DOM e trabalhar com ele.

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 os arquivos HTML são XHTML você sempre pode usar a classe XmlDocument para interpretá-lo. Você poderia, então, facilmente olhar para o corpo elemento e acrescentar um elemento filho a ele. Isso colocaria o elemento direito antes do fechamento tag.

Você pode querer olhar usando a agilidade Pacote Html

http://www.codeplex.com/htmlagilitypack

Eu não tenho certeza se o conteúdo exemplo, você deseja adicionar após a tag é a correta ou não, mas se for, eu estou vendo dois problemas:

  1. O código do Google Analytics deve ser adicionado imediatamente antes da end tag , e não a marca de abertura. Que garante que você não tem que esperar por ele para carregar antes de carregar seu próprio código.
  2. Se você está adicionando algum outro javascript, por que não acrescentar que em um arquivo externo, e executar que um onload em vez disso?

Espero que isso seja de alguma ajuda:)

Isto é o que eu tenho

sinta-se livre para fazer sugestões

 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();
        }
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top