简体   繁体   中英

Selenium - Writing a file to codemirror with line breaks

I'm writing a selenium test which writes a JSON file to a CodeMirror window. Here's my code so far:

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);

}

This code works. But it writes the whole JSON file on one line. Here's a few things I tried.

  1. Not replacing the "\\n". This gives an "unterminated string literal" error
  2. Replacing "\\n" with "\\r". Same error.
  3. Replacing "\\n" with "<\\br>" (without that backslash. I can't even do line breaks right on stack overflow). This just put a bunch of "br" tags in the json text.

Any ideas? I'm guessing there is a way to do this line by line, but I'd rather be able to just send the whole file as one string.

To get rid of line breaks

Try:

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM