Обтекание элементов не переносит их, исключение не показано - PullRequest
0 голосов
/ 17 марта 2019

Я хочу обернуть каждый Element моего документа JSouped. Эти Elements определяются в соответствии с наличием слова color в значении свойства style.

Документ: <body><span style="color: rgb(37, 163, 73);">Test</span></body>.

Итак, я написал:

Document jsoup_document_caption = Jsoup.parse("<body><span style=\"color: rgb(37, 163, 73);\">Test</span></body>");
Elements elements = jsoup_document_caption.getElementsByAttributeValueContaining("style", "color");
Elements jsouped_elements = elements.wrap("<div></div>");
String jsouped_caption = jsouped_elements.outerHtml();

Каждая из трех последних строк при печати показывает: <span style="color: rgb(37, 163, 73);">Test</span>.

Учитывая, в частности System.out.println(jsouped_caption), мы можем видеть, что он не был упакован. Ты знаешь почему? Я внимательно прочитал документ, но не нашел ответа: https://jsoup.org/apidocs/org/jsoup/select/Elements.html + https://jsoup.org/cookbook/.


Edit:

То же самое, если я лечу Element от Element:

    Elements elements = jsoup_document_caption.getElementsByAttributeValueContaining("style", "color");
    for(Element element : elements) {
        System.out.println("Found element:");
        System.out.println(element);
        Element jsouped_element = element.wrap("<div></div>");
        System.out.println("JSouped:");
        String jsouped_caption = jsouped_element.outerHtml();
        System.out.println(jsouped_caption);
    }

1 Ответ

2 голосов
/ 17 марта 2019

После того, как вы wrap элемент, обертка находится вне самого элемента - он становится его родителем, так что вы можете сделать это:

Document jsoup_document_caption = Jsoup.parse("<body><span style=\"color: rgb(37, 163, 73);\">Test</span></body>");
Elements elements = jsoup_document_caption.getElementsByAttributeValueContaining("style", "color");
System.out.println(elements); //outputs your original selection -<span style="color: rgb(37, 163, 73);">Test</span>
elements.wrap("<div/></div>");
System.out.println(elements); //still the same output - elements is unchanged
Element wrapped = elements.parents().first(); //now you have the original element AND the wrap
System.out.println(wrapped);    

Выход последнего отпечатка равен <div> <span style="color: rgb(37, 163, 73);">Test</span> </div>

...