|
本帖最后由 hbghlyj 于 2023-7-19 04:42 编辑 - function convertToTikZTree(ulElement,inside=0) {
- let tikzTree = inside ? '' : '\\begin{tikzpicture}\n\\node{Root}';
- // Loop through each list item
- for (let i = 0; i < ulElement.children.length; i++) {
- const liElement = ulElement.children[i];
- // Join content of child textnodes
- const text = [...liElement.childNodes].map(elm => elm.nodeType == 1?'':elm.textContent.trim()).join('')
- // Add node
- tikzTree += ' child{node{' + text + '}'
- // Check if the node has children
- if (liElement.querySelector('ul')) {
- // Add child nodes recursively
- tikzTree += convertToTikZTree(liElement.querySelector('ul'),1);
- }
- // Close child
- tikzTree += '}'
- }
- tikzTree += inside ? "" : ";\n\\end{tikzpicture}";
- return tikzTree
- }
复制代码
例子
- const str = '<ul id="nestedList"><li>1<ul><li>1.1</li><li>1.2</li></ul></li><li>2<ul><li>2.1</li><li><ul><li>2.1.1</li><li>2.1.2</li></ul>2.2</li></ul></li></ul>';
- const parser = new DOMParser();
- const ulElement = parser.parseFromString(str, 'text/xml').getElementById('nestedList');
- console.log(convertToTikZTree(ulElement));
复制代码 输出

图中1.2和2.1重叠了(因为与Root,1,2组成了▱平行四边形)
添加child[missing]避免重叠:

或加长子树的level distance避免重叠:

或缩短子树的sibling distance避免重叠:
 |
|