gpt4 book ai didi

xml - Flutter/Dart XML添加和插入节点

转载 作者:行者123 更新时间:2023-12-03 03:53:41 25 4
gpt4 key购买 nike

我正在尝试使用XML library for Flutter,但无法理解有关插入和添加节点的自述文件部分。

自述文件中说:“您需要先创建一个副本,否则会引发XmlParentError”。这是我遇到的错误,但是我不明白创建副本的含义或执行该操作的方式。

目前,我的代码非常简单:

    builder = new XmlBuilder();
XmlDocument document = buildParagraphXML();
print(document.toXmlString(pretty: true, indent: '\t')); //this prints the xml correctly
document.children.add(buildParagraphXML());
print(document.toXmlString(pretty: true, indent: '\t')); //this throws the XMLParentError

buildParagraphXML() {
builder.element('paragraphblock', nest: () {
builder.attribute('paragraphid', '1');
builder.attribute('title', 'Paragraph 1');
builder.text('content of paragraph');
});
final paragraphXML = builder.build();
return paragraphXML;
}

第一次打印返回的准确XML为:
<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>

第二个应该返回:
<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>
<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>

但抛出XML父错误。 Unhandled Exception: Node already has a parent, copy or remove it first:,但我不明白“复制或删除它”是什么意思...

然后,我希望能够在每个段落中添加子节点,以此类推,在树的更深处。

最佳答案

我看到的第一个问题是您多次重复使用构建器。我同意该错误消息有点误导性:发生该错误是因为将其以前的<paragraphblock>重新添加到了新文档中。您可能打算将构建器的创建移到您的方法中,使其看起来像:

XmlDocument buildParagraphXML() {
final builder = new XmlBuilder();
builder.element('paragraphblock', nest: () {
// etc ...
});
return builder.build();
}

然后,我在 document.children.add(buildParagraphXML());行中看到了下一个问题,该行试图将一个文档添加到另一个文档。如果您从构建器开始,那么理想情况下,您将使用构建器来构建完整的文档。如果要按照自己的方式进行操作,则必须从第二个文档中提取第一个元素,然后将其复制并添加到第一个文档中,如下所示:

document.children.add(buildParagraphXML().firstChild.copy());

请注意,虽然上面的代码有效,但是生成的文档无效,因为它包含多个根元素。

关于xml - Flutter/Dart XML添加和插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62156451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com