【发布时间】:2020-11-18 20:21:23
【问题描述】:
原文:
我想从字符串中删除第一个 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);
}
}
【问题讨论】:
-
有 - 文字是什么样的?它从何而来?它是 XML 还是 HTML?您可以使用正则表达式,或者,如果它是 XML,则可以使用 XML 库并检索您想要的标签或元素的内部文本。如果
body是 XmlDocument 或 XDocument,您可以检索所需的节点并获取其内部文本,而无需转换为字符串 -
如果这是 XML,您应该不自行操作它。相反,您应该将其反序列化为一个对象并对其进行操作。
-
@PanagiotisKanavos 原始主体是 JSON,其中包含 HTML 代码作为值。我想从 JSON 中提取 HTML 代码
-
@Nina 然后解析 json 并使用解析后的对象来获取它。