简体   繁体   English

在html中找到body标记结束的最佳方法

[英]best way to find end of body tag in html

I'm writing a program to add some code to html files 我正在编写一个程序来为html文件添加一些代码

I was going to use a series of indexof and loops to find what is essentially ""X (where X is the spot im looking for) 我打算用一系列的indexof和循环来找到什么本质上是“”X(其中X是我正在寻找的地方)

It occurred to me that there might be a more eloquent way of doing this 在我看来,可能有一种更有说服力的方式来做到这一点

does anyone have any suggestions. 有没有人有什么建议。

what it looks like currently 它目前的样子

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

what it should look like when im done 我完成后应该是什么样子


<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>

I'm not sure I'm understanding you, but do you mean this? 我不确定我是否理解你,但你的意思是这个吗?

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

And it's probably obvious I don't know c#... You'd probably want to make the "body" tag case insensitive via regexps. 而且很明显我不知道c#...你可能想通过regexp使“body”标签不区分大小写。

我建议使用HtmlAgilityPack将html解析为DOM并使用它。

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;
}

If the HTML files are valid XHTML you could always use the XmlDocument class to interpret it. 如果HTML文件是有效的XHTML,您可以始终使用XmlDocument类来解释它。 You could then easily look for the body element and append a child element to it. 然后,您可以轻松查找body元素并向其添加子元素。 This would place the element right before the closing </body> tag. 这会将元素放在结束</ body>标记之前。

You might want to look at using the Html Agility Pack 您可能希望查看使用Html Agility Pack

http://www.codeplex.com/htmlagilitypack http://www.codeplex.com/htmlagilitypack

I'm not sure whether the example content you want to add after the tag is the correct one or not, but if it is, I'm seeing two problems: 我不确定您要在标签之后添加的示例内容是否正确,但如果是,我会看到两个问题:

  1. The Google Analytics code should be added just before the end tag , not the opening tag. 应在结束标记之前添加Google Analytics代码,而不是在开始标记之前添加。 That ensures that you don't have to wait for it to load before loading your own code. 这可确保您在加载自己的代码之前不必等待它加载。
  2. If you're adding some other javascript, why not add that in an external file, and execute that one onload instead? 如果你要添加一些其他的javascript,为什么不在外部文件中添加它,并执行那个onload呢?

Hope that's of some help :) 希望有一些帮助:)

This is what i got 这就是我得到的

feel free to make suggestions 随意提出建议

 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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM