How to make a Node from a String?

2019-07-06 00:37发布

问题:

I need help with one problem.

I have an Element called e.g. myElement. I have also some strings and elements (generally nodes), which I want to add as myElement's children (all of the same level). My idea looks like this piece of code:

DivElement div1=new DivElement();
// ... some parameters of div1
String string1="Hello";
DivElement div2=new DivElement();
// ... some parameters of div2
String string2="World!";

DivElement myElement=new DivElement();
myElement.nodes.addAll([div1,string1,div2,string2]);

But this don't work, because Strings are not Nodes. How could I make a Node from a String?

回答1:

You can only add Node's to the element's node list. However you can create a Text node from a string.

For example:

myElement.nodes.addAll([div1, new Text(string1), div2, new Text(string2)]);


回答2:

see also https://stackoverflow.com/a/22065859/217408

You can create an element by parsing HTML text:

new Element.html("YOUR HTML STRING HERE");

see Dart: Up and Running CH03

EDIT
You may need to pass a NodeValidator to get the entire text rendered like:

NodeValidator nodeValidator = new NodeValidatorBuilder()
    ..allowTextElements();
    // ..allowHtml5()
    // ..allowElement('Button', attributes: ['ng-disabled']);

new Element.html("YOUR HTML STRING HERE", validator: nodeValidator);

If you run the application you get log messages like "element/attribute xxx removed from ..." if some of the text was not accepted by the NodeValidator.



标签: dart