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

标签 c# html json

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/

相关文章:

javascript - 是否可以用漂亮的汤从动态图中提取数据?

javascript - 从 json 对象中的多个路径获取值列表

c# - 使用 Powershell RunspacePool 多线程从 C# 到远程服务器

c# - 私有(private)集或私有(private)成员?

c# - System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached

c# - 如何验证typemock中私有(private)方法调用的数量

html - 如何在内联 CSS 中插入引号?

javascript - 如何重新初始化 Owl Carousel 2.0?

html - 通过 Json Pipe Angular 9 项目显示 ngForm 数据不显示任何数据。将循环结构转换为 JSON 错误

javascript - 如何将 javascript 对象放入数据表 JSON 中?