小程序rich-text組件——java解析html輸出(out)json

  1. 新聞資訊
  2. 技術百科
行業動态 公司新聞 案例分享 技術百科

小程序rich-text組件——java解析html輸出(out)json

來(Come)源:奇站網絡 浏覽量:2248 發布日期: 2018-03-09

  1. <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
  2. <dependency>
  3. <groupId>org.jsoup</groupId>
  4. <artifactId>jsoup</artifactId>
  5. <version>1.11.2</version>
  6. </dependency>
  1. public class RichTextParse {
  2. public static List<Object> parse(String body) throws Exception {
  3. List<Object> nodes = new ArrayList<Object>();
  4. Document doc = Jsoup.parse(body);
  5. Element rootElement = doc.body();
  6. for (Element element : rootElement.children()) {
  7. RichTextNode node = new RichTextNode();
  8. node.setName(element.nodeName());
  9. // attrs
  10. for (Attribute attr : element.attributes()) {
  11. node.getAttrs().put(attr.getKey(), attr.getValue());
  12. }
  13. // has children
  14. if (element.children().size() > 0) {
  15. loopElement(node, element);
  16. } else {
  17. RichTextNodeText nodeText = new RichTextNodeText();
  18. nodeText.setType("text");
  19. nodeText.setText(element.text());
  20. node.getChildren().add(nodeText);
  21. }
  22. // add to nodes
  23. nodes.add(node);
  24. }
  25. return nodes;
  26. }
  27. private static void loopElement(RichTextNode nodeParent, Element elementParent) {
  28. List<Element> eles = elementParent.children();
  29. for (Element element : eles) {
  30. RichTextNode node = new RichTextNode();
  31. node.setName(element.nodeName());
  32. // attrs
  33. for (Attribute attr : element.attributes()) {
  34. node.getAttrs().put(attr.getKey(), attr.getValue());
  35. }
  36. //
  37. switch (element.nodeName()) {
  38. case "img":
  39. node.getAttrs().put("style", "max-width:100%;height:auto;");
  40. break;
  41. default:
  42. break;
  43. }
  44. // has children
  45. if (element.children().size() > 0) {
  46. loopElement(node, element);
  47. } else {
  48. RichTextNodeText nodeText = new RichTextNodeText();
  49. nodeText.setType("text");
  50. nodeText.setText(element.text());
  51. node.getChildren().add(nodeText);
  52. }
  53. // add to parent node
  54. nodeParent.getChildren().add(node);
  55. }
  56. }
  57. }
标簽:

廈門極極網絡科技有限公司

電話:13313868605

QQ:3413772931

地(land)址:廈門集美區軟件園三期


                    掃一(one)掃加我(I)咨詢