Recursively add node to child elements #145
-
I making a conversor. I need to change every text node element, adding a node inside it. But when i try this, i got a infinite loop. How can i handle it? var doc = xml_parser.XmlDocument.parse(Utf8Codec().decode(chapterContent));
Iterable<xml_parser.XmlElement> elements = doc.findAllElements('*');
for (var i = 0; i < elements.length; i++) {
var element = elements.elementAt(i);
element.innerXml = '<div class="test">${element.innerText}</div>';
... i also tried this code... var doc = xml_parser.XmlDocument.parse(Utf8Codec().decode(chapterContent));
var descendants = doc.descendants;
for (var i = 0; i < descendants.length; i++) {
var node = descendants.elementAt(i);
if (node is xml_parser.XmlText && !node.text.trim().isEmpty) {
node.innerXml = '<div class="test">${node.text}</div>';
}
} But got this error: |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
The problem is that both of your iterables final elements = doc.findAllElements('*').toList();
final descendants = doc.descendants.toList(); The problem with the second snippet is that |
Beta Was this translation helpful? Give feedback.
-
To.list works...
But the problem is when trying replace node, and the element have a text
node plus another xml element. For exemple:
```
h2>Text exemple <strong>with strong</strong></h2>
```
Em qua., 25 de mai. de 2022 às 05:39, Lukas Renggli <
***@***.***> escreveu:
The problem is that both of your iterables elements and descendants are
lazy, that is they re-evaluate the query on each interaction (i.e. when
calling length or elementAt). I recommend that you convert the resulting
iterables to a list first. Then the elements of the list are only computed
once at the beginning of your code.
final elements = doc.findAllElements('*').toList();final descendants = doc.descendants.toList();
The problem with the second snippet is that XmlText has no children and
therefor you cannot call innerXml on it. You would want to call it on the
parent element, i.e. node.parentElement.innerXml = '...'. I agree that
the error message is not very clear.
—
Reply to this email directly, view it on GitHub
<#145 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AGPTWARU2YKVD6EISRZ45GLVLXRMJANCNFSM5W3TYM3Q>
.
You are receiving this because you authored the thread.Message ID:
***@***.***>
--
Att.
Filipe Nanclarez
|
Beta Was this translation helpful? Give feedback.
-
Works with this: var descendants = doc.descendants.toList();
for (var i = 0; i < descendants.length; i++) {
var node = descendants.elementAt(i);
if (node is xml_parser.XmlText && !node.text.trim().isEmpty) {
var newNode = xml_parser.XmlElement(xml_parser.XmlName('div'));
newNode.innerXml = '<span>test</span>';
node.replace(newNode);
}
} Thanks! |
Beta Was this translation helpful? Give feedback.
Works with this:
Thanks!