[英]Inject some string to a specific part of string in C#
如何將一些字符串插入另一個字符串的特定部分。 我想要實現的是我在我的變量中有一個像這樣的html字符串string stringContent;
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="Viewport" content="width=320; user-scaleable=no;
initial-scale=1.0">
<style type="text/css">
body {
background: black;
color: #80c0c0;
}
</style>
<script>
</script>
</head>
<body>
<button type="button" onclick="callNative();">Call to Native
Code!</button>
<br><br>
</body></html>
我需要在<script> <script/>
標記內添加以下字符串內容
function callNative()
{
window.external.notify("Uulalaa!");
}
function addToBody(text)
{
document.body.innerHTML = document.body.innerHTML + "<br>" + text;
}
我怎樣才能在C#中實現這一目標。
假設您的內容存儲在字符串content
,您可以首先找到腳本標記:
int scriptpos = content.IndexOf("<script");
然后超過腳本標記的結尾:
scriptpos = content.IndexOf(">", scriptpos) + 1;
最后插入新內容:
content = content.Insert(scriptpos, newContent);
這至少允許腳本標記中的潛在屬性。
使用htmlString.Replace(what, with)
var htmlString = "you html bla bla where's the script tag? oooups here it is!!!<script></script>";
var yourScript = "alert('HA-HA-HA!!!')";
htmlString = htmlString.Replace("<script>", "<script>" + yourScript);
請注意,這將在所有<script>
元素中插入yourScript
。
var htmlString = @"<script>$var1</script> <script>$var2</script>"
.Replace("$var1", "alert('var1')")
.Replace("$var2", "alert('var2')");
var htmlString = "you html bla bla where's the script tag? oooups here it is!!!<script></script>";
var yourScript = "alert('HA-HA-HA!!!')";
htmlString = htmlString.Insert(html.IndexOf("<script>") + "<script>".Length + 1, yourScript);
為此,您可以使用File.ReadAllText方法將html文件讀入字符串。 這里例如,我使用了樣本html字符串。 之后,通過一些字符串操作,您可以在腳本下添加標簽,如下所示。
string text = "<test> 10 </test>";
string htmlString =
@" <html>
<head>
<script>
<tag1> 5 </tag1>
</script>
</head>
</html>";
int startIndex = htmlString.IndexOf("<script>");
int length = htmlString.IndexOf("</script>") - startIndex;
string scriptTag = htmlString.Substring(startIndex, length) + "</script>";
string expectedScripTag = scriptTag.Replace("<script>", "<script><br>" + text);
htmlString = htmlString.Replace(scriptTag, expectedScripTag);
這可以使用HTML Agility Pack (開源項目http://htmlagilitypack.codeplex.com )以另一種(更安全)的方式完成。 它可以幫助您解析和編輯HTML,而無需擔心格式錯誤的標簽( <br/>, <br />, < br / >
等等)。 它包括一些操作,可以輕松插入元素,如AppendChild
。
如果您正在處理HTML,這是要走的路。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.