Я использую следующую версию JSoup (вместе с Java 1.7):
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
Мой код:
public class HtmlTagUtils {
private static String mockHtml = "<asset-entity type=\"photo\" id=\"1236ad76-7433-fs34-50d1-b12bdbc308899af\">"
+ "</asset-entity>\r\nAngelie Jolie was seen at Wholefoods with ex-beau Brad Pitt.\r\n <asset-entity type=\"photo\" id=\"2346fe7d-c175-c380-4ab2-dda068b42b033dvf\">"
+ "</asset-entity>\r\n- The majority of their kids were with them.\r\n<asset-entity type=\"video\" id=\"45064086-5d85-1866-4afc-a523c04c2b3e43b6\"> </asset-entity>\r\n";
public static List<String> extractIdsForPhotos(String html) {
Document doc = Jsoup.parse(html);
Elements elements = doc.select("asset-entity[type=photo]");
List<String> photos = new ArrayList<>();
for (Element element : elements) {
String type = element.attributes().get("type");
String id = element.attributes().get("id");
photos.add(id);
}
return photos;
}
public static List<String> extractIdsForVideos(String html) {
Document doc = Jsoup.parse(html);
Elements elements = doc.select("asset-entity[type=video]");
List<String> videos = new ArrayList<>();
for (Element element : elements) {
String type = element.attributes().get("type");
String id = element.attributes().get("id");
videos.add(id);
}
return videos;
}
public static void main (String args []) {
List<String> photoIds = extractIdsForPhotos(mockHtml);
for (String photoId : photoIds) {
System.out.println("\n\tphotoId: " + photoId);
}
List<String> videoIds = extractIdsForVideos(mockHtml);
for (String videoId : videoIds) {
System.out.println("\n\tvideoId: " + videoId);
}
}
}
Получите следующий вывод на стандартный вывод:
photoId: 1236ad76-7433-fs34-50d1-b12bdbc308899af
photoId: 2346fe7d-c175-c380-4ab2-dda068b42b033dvf
videoId: 45064086-5d85-1866-4afc-a523c04c2b3e43b6
Я могу найти необходимые активы на основе этих идентификаторов, но мой вопрос заключается в том, как заменить весь тег (вместе с его содержимым, встроенный) с помощью JSoup (например, для фотографий):
<asset-entity type=\"photo\" id=\"4806ad76-7433-fs34-50d1-b12bdbc308899ad\">" + "</asset-entity>
с:
<img src="AngelinaJolie.jpg">
Таким образом, преобразованный HTML будет выглядеть так:
"<img src="AngelinaJolie.jpg">\r\nAngelie Jolie was seen at Wholefoods with ex-beau Brad Pitt.\r\n <img src="BradPitt.jpg">
\r\n- The majority of their kids were with them.\r\n<video><source src="Brangelina.mp4" type="video/mp4"></video>\r\n";
Может кто-нибудь указать мне правильное направление?