gpt4 book ai didi

c# - 使用 C# 将 HTML 字符串作为 JSON 输出

转载 作者:行者123 更新时间:2023-11-28 00:49:59 26 4
gpt4 key购买 nike

HTML 字符串作为使用 C# 的 JSON 输出。

我想用 ' 替换 HTML 包装器 < 和 > 之间的 "的每个实例,同时转换为 JSON。同时如果它有带有 "引号的文本,那么它不应该被替换为 ' 引号。例如。 “自 1500 年代以来”

代码 - 将所有 "替换为 ' 引号

public string Content
{
get
{
return _content;
}
set
{
if (value != null)
{
this._content = this._content.Replace("\"", "'");
}
}
}

我正在从我的 View 中获取这种形式的字符串。

E.g.  model.Content = "<p> Lorem Ipsum is simply dummy text of the printing <span id= "#" ids= "#" display= "inline" ></ span > and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever "since the 1500s".<br></p>";

我正在使用 JsonConvert.SerializeObject

string output = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

预期字符串 - HTML 标记中的所有双引号都应转换为单引号,但文本引号应与使用 C# 时一样

 "content": "<p><b>Lorem Ipsum</b> is simply dummy <i>text </i>of the printing&nbsp;<span id='#' ids='#' display='inline'></span> and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever \"since the 1500s\".</p>",

最佳答案

我想你想用 '. 替换 < 和 > 之间的每个 "实例。

因此,您在字符串中查找每个 ",在后面查找 <,在前面查找 >。正则表达式如下所示:

(?<=\<[^<>]*)"(?=[^><]*\>)

所以你可以使用

outputString = Regex.Replace(inputString, "(?<=\\<[^<>]*)\"(?=[^><]*\\>)", "'");

然后你想在你的字符串中转义其他 "。为此你可以使用

outputString = outputString.Replace(@"""", @"\""");

outputString = outputString.Replace("\"", "\\\"");

我创建了一个控制台应用程序来测试它,

 Console.WriteLine("Enter The String : ");
string input = Console.ReadLine();
string pattern = "(?<=\\<[^<>]*)\"(?=[^><]*\\>)";
string output = Regex.Replace(input, pattern, "'");
output = output.Replace(@"""", @"\""");
Console.WriteLine(output);
Console.ReadKey();

输入字符串是你提供的字符串,然后输出将是,

<p> Lorem Ipsum is simply dummy text of the printing <span id= '#' ids= '#' display= 'inline' ></ span > and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever \"since the 1500s\".<br></p>

关于c# - 使用 C# 将 HTML 字符串作为 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com