c# - C# - 从 JSON 中提取 HTML
问题描述
原文:
我想从字符串中删除第一个之前IndexOf("<")
和之后的字符LastIndexOf(">")
。
可能有比我所做的更有效的方法来做到这一点。我现在的问题是,谁能告诉我这种有效的方式(如果有的话)?
我的代码:
string body_string = body.ToString();
string new_body = body_string.Substring(0, body_string.LastIndexOf(">") + 1);
string htmlbody = new_body.Substring(new_body.IndexOf("<"));
谢谢!
更新:
我意识到我最初的问题不是我真正想要的,所以我再试一次。
我在 Confluence 页面上通过 REST API 使用了 GET 方法。我得到的是一个带有来自页面内容的 HTML 代码作为值的 JSON。现在我想对 JSON 进行某种“过滤”,以便只从中获取 HTML。
正如您在我上面的代码中看到的那样,我最初的想法是将 JSON 转换为字符串,然后对其进行过滤,但可能有一种更有效的方法来做到这一点。
我怎样才能做到这一点?
代码:
public static class Http
{
private static HttpClient httpClient = new HttpClient();
[FunctionName("Http")]
public static async Task<IActionResult> getContentByID(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
//Set up Configuration Builder
var confBuild = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json")
.AddEnvironmentVariables()
.Build();
//Basic Authentication
var user = confBuild["ConfluenceUser"];
var api = confBuild["ConfluenceAPI"];
var domain = confBuild["ConfluenceDomain"];
httpClient.DefaultRequestHeaders.Authorization= new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", user, api))));
object body;
string new_body, htmlbody;
//Get content from page
using (HttpResponseMessage response = await httpClient.GetAsync(
$"https://{domain}/wiki/rest/api/content/{id}?expand=body.storage"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
body = JsonConvert.DeserializeObject(responseBody);
string body_string = body.ToString();
//Extract HTML from JSON
new_body = body_string.Substring(0, body_string.LastIndexOf(">") + 1);
htmlbody = new_body.Substring(new_body.IndexOf("<"));
}
return new OkObjectResult(htmlbody);
}
}
解决方案
只需取(“<”的第一个索引)和(“>”的最后一个索引)之间的子字符串:
string input = "<Some String>";
int startIndex = input.IndexOf("<"); //return firs appear index of "<"
int endIndex = input.LastIndexOf(">");
int count = (endIndex - startIndex) -1;
string result = input.Substring(startIndex + 1,count); //Substring starts at (startIndex) and have (count) legth!
结果 = 一些字符串
推荐阅读
- pandas - pandas 需要 xlrd 1.1.0 版本,但 styleframe 应该有 xlrd 1.0.0。如何正确设置它,以便我需要 styleframe 和 pandas?
- python - 为什么我的函数返回对象标识而不是“ip”变量?
- javascript - react-native-web monorepo 架构中尝试导入错误
- docker - 在运行映像时以传递给它的任意用户身份运行 docker 容器
- php - PHP GET,使用URL友好而不是来自ID?
- sql-server - 用于创建表的 T-SQL 语法
- sql-server - 有什么方法可以从 Oracle 存储过程执行 SQL Server 过程?
- servlets - Laradock 中的 Solr Instace 使用什么 JavaServlet?
- python - tkinter.Button.configure() 返回的值是什么
- python - 将字典添加到熊猫数据框中并忽略额外的值