找回密码
 快速注册
搜索
查看: 36|回复: 0

HTML列表转换为TikZ tree

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2023-7-19 03:15 |阅读模式
本帖最后由 hbghlyj 于 2023-7-19 04:42 编辑
  1. function convertToTikZTree(ulElement,inside=0) {
  2.   let tikzTree = inside ? '' : '\\begin{tikzpicture}\n\\node{Root}';
  3.   // Loop through each list item
  4.   for (let i = 0; i < ulElement.children.length; i++) {
  5.     const liElement = ulElement.children[i];
  6.     // Join content of child textnodes
  7.     const text = [...liElement.childNodes].map(elm => elm.nodeType == 1?'':elm.textContent.trim()).join('')
  8.     // Add node
  9.     tikzTree += ' child{node{' + text + '}'
  10.     // Check if the node has children
  11.     if (liElement.querySelector('ul')) {
  12.       // Add child nodes recursively
  13.       tikzTree += convertToTikZTree(liElement.querySelector('ul'),1);
  14.     }
  15.     // Close child
  16.     tikzTree += '}'
  17.   }
  18.   tikzTree += inside ? "" : ";\n\\end{tikzpicture}";
  19.   return tikzTree
  20. }
复制代码

例子
  1. 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>';
  2. const parser = new DOMParser();
  3. const ulElement = parser.parseFromString(str, 'text/xml').getElementById('nestedList');
  4. console.log(convertToTikZTree(ulElement));
复制代码
输出

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

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

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

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 12:09

Powered by Discuz!

× 快速回复 返回顶部 返回列表