在 html 中查找 body 标记结尾的最佳方法

发布于 2024-07-29 03:30:59 字数 970 浏览 6 评论 0原文

我正在编写一个程序来向html文件添加一些代码

我将使用一系列indexof和循环来查找本质上是“”X的内容 (其中 X 是我正在寻找的位置)

我想到可能有一种更雄辩的方式来做到这一点

,有人有任何建议吗?

目前的样子

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

完成后应该是什么样子


<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 writing a program to add some code to html files

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)

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

橙味迷妹 2024-08-05 03:30:59

我不确定我是否理解你的意思,但你是这个意思吗?

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

很明显我不懂 C#...您可能想通过正则表达式使“body”标记不区分大小写。

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.

沧笙踏歌 2024-08-05 03:30:59

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

I would recommend to use HtmlAgilityPack to parse the html into DOM and work with it.

笑饮青盏花 2024-08-05 03:30:59
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;
}
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;
}
原来分手还会想你 2024-08-05 03:30:59

如果 HTML 文件是有效的 XHTML,您始终可以使用 XmlDocument 类来解释它。 然后,您可以轻松查找 body 元素并向其附加一个子元素。 这会将元素放置在结束 标记之前。

If the HTML files are valid XHTML you could always use the XmlDocument class to interpret it. You could then easily look for the body element and append a child element to it. This would place the element right before the closing </body> tag.

谜泪 2024-08-05 03:30:59

您可能想了解如何使用 Html Agility Pack

http://www.codeplex.com/htmlagilitypack

You might want to look at using the Html Agility Pack

http://www.codeplex.com/htmlagilitypack

◇流星雨 2024-08-05 03:30:59

我不确定您要在标记后添加的示例内容是否正确,但如果是,我会看到两个问题:

  1. Google Analytics 代码应添加在 结束标记之前,而不是开始标签。 这确保您不必等待它加载即可加载您自己的代码。
  2. 如果您要添加一些其他 javascript,为什么不将其添加到外部文件中,然后执行 onload 呢?

希望这对您有所帮助:)

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

Hope that's of some help :)

痴情 2024-08-05 03:30:59

这就是我得到的,

请随意提出建议

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

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();
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文