Forgot password?
 Create new account
View 127|Reply 0

HTML列表转换为TikZ tree

[Copy link]

3148

Threads

8489

Posts

610K

Credits

Credits
66148
QQ

Show all posts

hbghlyj Posted at 2023-7-19 03:15:25 |Read mode
Last edited by hbghlyj at 2023-7-19 04:42:00
  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. }
Copy the Code

例子
  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));
Copy the Code
输出

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

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

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

手机版Mobile version|Leisure Math Forum

2025-4-20 12:19 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list