首页 > 解决方案 > 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);
        }
    }

标签: c#htmljson

解决方案


只需取(“<”的第一个索引)和(“>”的最后一个索引)之间的子字符串:

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!

结果 = 一些字符串


推荐阅读