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- TestA1
- TestB1
- TestA2
- TestB2
输出:
1. Test1
a. TestA1
b. TestB1
2. Test2
a. TestA2
b. TestB2
而已! 🙂