Selenium-使用换行符将文件写入代码镜像

Selenium - Writing a file to codemirror with line breaks

本文关键字:代码 镜像 文件 换行符 Selenium-      更新时间:2024-05-08

我正在编写一个selenium测试,它将JSON文件写入CodeMirror窗口。到目前为止,这是我的代码:

public void setJson(String jsonPath) throws IOException, InterruptedException {
    // Read a file to a string
    byte[] encoded = Files.readAllBytes(Paths.get(jsonPath));
    String jsonText = new String(encoded, StandardCharsets.UTF_8);
    // Get rid of line breaks
    jsonText = jsonText.replace("'n", "");
    // Escape the quotes
    jsonText = jsonText.replace("'"", "'''"");
    // Write to the CodeMirror
    WebElement queryInput = driver.findElement(By.xpath("//*[@id='"content'"]/div/div[2]/div/div[1]/div[1]/div/div/div/div"));
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].CodeMirror.setValue('"" + jsonText + "'");", queryInput);
}

此代码有效。但它将整个JSON文件写在一行中。以下是我试过的一些东西。

  1. 不替换"''n"。这会产生"未终止的字符串文字"错误
  2. 将"''n"替换为"''r"。同样的错误
  3. 将"''n"替换为"<''br>"(没有反斜杠。我甚至不能在堆栈溢出时换行)。这只是在json文本中放了一堆"br"标记

有什么想法吗?我想有一种方法可以逐行完成,但我宁愿将整个文件作为一个字符串发送。

去除换行

尝试:

jsonText = jsonText.replaceAll("'n", "''''''''''''''''r''''''''''''''''n"); // for all occurrence
// This will replace 'n with ''''r''''n a new line for codemirror

jsonText = jsonText.replace("'n", "''''''''''''''''r''''''''''''''''n");