createFragment 方法

DocumentFragment createFragment(
  1. String? svg,
  2. {NodeValidator? validator,
  3. NodeTreeSanitizer? treeSanitizer}
)
override

从 HTML 片段创建 DocumentFragment 并确保它遵循验证器或 treeSanitizer 指定的消毒规则。

如果默认的验证行为过于严格,则应创建一个新的 NodeValidator,可以扩展或包装默认验证器并覆盖验证 API。

treeSanitizer 用于遍历生成的节点树并对其进行消毒。也可以提供自定义的 treeSanitizer 以执行特殊的验证规则,但由于 API 实现较复杂,因此不建议这样做。

返回的树保证仅包含验证器允许的节点和属性。

另请参阅

实现

DocumentFragment createFragment(String? svg,
    {NodeValidator? validator, NodeTreeSanitizer? treeSanitizer}) {
  if (treeSanitizer == null) {
    if (validator == null) {
      validator = new NodeValidatorBuilder.common()..allowSvg();
    }
    treeSanitizer = new NodeTreeSanitizer(validator);
  }

  // We create a fragment which will parse in the HTML parser
  var html = '<svg version="1.1">$svg</svg>';
  var fragment =
      document.body!.createFragment(html, treeSanitizer: treeSanitizer);

  var svgFragment = new DocumentFragment();
  // The root is the <svg/> element, need to pull out the contents.
  var root = fragment.nodes.single;
  while (root.firstChild != null) {
    svgFragment.append(root.firstChild!);
  }
  return svgFragment;
}