公司新闻 行业动态 技术分享

小程序rich-text组件——java解析html输出json

发布日期: 2018-03-09浏览次数: 601

  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

地址:厦门软件园三期A02

网站地图