java格式html_java – HTML格式化文本

jsoup到“格式化文本”没有api,但您可以自己转换列表:

>遍历ul / ol元素的所有子元素,这是列表的根

> if item:format并添加输出String

> if sublist:do 1. – 但是使用sublist元素 – 并添加结果

例:

在这个例子中,我使用type属性来确定需要什么类型的项目符号,并使用字符(!)来索引项目.如果没有合适的属性,则使用char 1.

执行:

/**

* Convert the Listelement root to a formated string-representation.

*

* @param root Rootelement of the list (normally 'ul' or 'ol' tag)

* @param depth Depth of the list (=0 for root element)

* @return List as String

*/

public String createList(Element root, int depth)

{

final String indentation = createIndentation(depth); // create indentation

StringBuilder sb = new StringBuilder();

final String typeAttr = root.attr("type"); // Get the character used as bullet (= 'type' attribute)

char type = typeAttr.isEmpty() ? '1' : typeAttr.charAt(0); // if 'type' attribute: use it, else: use '1' instead

for( Element sub : root.children() ) // Iterate over all Childs

{

// If Java < 7: use if/else if/else here

switch( sub.tagName() ) // Check if the element is an item or a sublist

{

case "li": // Listitem, format and append

sb.append(indentation).append(type++).append(". ").append(sub.ownText()).append("\n");

break;

case "ol": // Sublist

case "ul":

if( !sub.children().isEmpty() ) // If sublist is not empty (contains furhter items)

{

sb.append(createList(sub, depth + 1)); // Recursive call for the sublist

}

break;

default: // "Illegal" tag, do furhter processing if required - output as an example here

System.err.println("Not implemented tag: " + sub.tagName());

}

}

return sb.toString(); // Return the formated List

}

/**

* Create an Indentationstring of length blanks.

*

* @param length Size of indentation

* @return Indentationstring

*/

private String createIndentation(int length)

{

StringBuilder sb = new StringBuilder(length);

for( int i=0; i

{

sb.append(' ');

}

return sb.toString();

}

Testcode:

Document doc = ... // Load / parse your document here

Element listRoot = doc.select("ol").first(); // Select the root-element (!) of the list here.

final String output = createList(listRoot, 0); // Convert the list

System.out.println(output); // Ouput

结果:

输入(HTML):

Test1
  1. TestA1
  2. TestB1
Test2
  1. TestA2
  2. TestB2

输出:

1. Test1

a. TestA1

b. TestB1

2. Test2

a. TestA2

b. TestB2

而已! 🙂

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值