【问题标题】:best way to find end of body tag in html在html中找到body标签结尾的最佳方法
【发布时间】:2010-11-13 12:32:58
【问题描述】:

我正在编写一个程序来将一些代码添加到 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>

【问题讨论】:

  • 清除我想在 标签后添加代码

标签: c# .net html winforms indexof


【解决方案1】:

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

【讨论】:

  • 我想这可能就像用大炮打苍蝇一样。我猜它的 html 是微不足道的事实。如果我要在 Windows 中进行搜索,那就是 indexof("");但索引不支持通配符
  • DOM 操作确实是最安全的方法,crash893。对对象的 HTML 序列化使用字符串操作就像使用锤子绘制蓝图一样。
  • 我可以在没有 DOM 的情况下在 17 行中完成,这可能更安全,但就像开坦克去教堂一样,我不需要那么安全
  • body 元素的开始和结束标签在 HTML 中是可选的,所以除非你想处理显式包含标签的页面子集……只需使用适当的解析器!
【解决方案2】:

您可能想看看使用 Html Agility Pack

http://www.codeplex.com/htmlagilitypack

【讨论】:

    【解决方案3】:

    如果 HTML 文件是有效的 XHTML,您总是可以使用 XmlDocument 类来解释它。然后,您可以轻松查找 body 元素并将子元素附加到它。这会将元素放置在结束

    【解决方案4】:

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

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

    而且很明显我不懂 c#...您可能希望通过正则表达式使“body”标签不区分大小写。

    【讨论】:

    • 或者您可以像其他一些答案一样使用整个 DOM 解析器。但是,如果这就是你所要做的,为什么还要加载额外的废话呢?
    • 这正是我想要做的,但不是在结束正文标签之前添加它
    【解决方案5】:

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

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

    希望对你有所帮助:)

    【讨论】:

      【解决方案6】:

      这就是我得到的

      欢迎提出建议

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

      【讨论】:

        【解决方案7】:
        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;
        }
        

        【讨论】:

          猜你喜欢
          • 2011-02-18
          • 1970-01-01
          • 2013-01-03
          • 1970-01-01
          • 1970-01-01
          • 2020-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多