使用XML::LibXML写XML时如何创建追加节点?

How to create nodes to append when using XML::LibXML to write XML?

我正在创建一个 XML 文档并在循环中向其添加一个复杂的节点,类似于以下示例。

以下有效,但感觉它的创建方式很笨拙 $row_template。是否没有一些更具体的方法来创建文档片段以从 xml 字符串中重用?

use 5.022;
use warnings;
use XML::LibXML;

my $xml = '<?xml version="1.0"?><RootNode><Outer1><Outer2/></Outer1></RootNode>';
my $row_parent_xpath = '//Outer2';
my $row_xml = '<DetailNode><Field1/><Field2/></DetailNode>';

# create the document
my $doc = XML::LibXML->load_xml('string' => $xml);
# find where we will be inserting nodes
my ($parent) = $doc->findnodes($row_parent_xpath);

# create a template for the nodes to insert
my $row_template = XML::LibXML->load_xml('string' => $row_xml)->documentElement;
$row_template->setOwnerDocument($doc);

for my $row_data ({field1=>'Foo',field2=>'Bar'}, {field1=>'Baz',field2=>'Quux'}) {
    my $row = $row_template->cloneNode(1);
    $parent->appendChild($row);
    $_->appendChild($doc->createTextNode($row_data->{field1})) for $row->findnodes('Field1');
    $_->appendChild($doc->createTextNode($row_data->{field2})) for $row->findnodes('Field2');
}

say $doc->toString(1);

输出:

<?xml version="1.0"?>
<RootNode>
  <Outer1>
    <Outer2>
      <DetailNode>
        <Field1>Foo</Field1>
        <Field2>Bar</Field2>
      </DetailNode>
      <DetailNode>
        <Field1>Baz</Field1>
        <Field2>Quux</Field2>
      </DetailNode>
    </Outer2>
  </Outer1>
</RootNode>

libxml2 有 xmlParseBalancedChunkMemory which also takes a document. XML::LibXML has parse_balanced_chunk 但这不允许设置文档。我不确定您是否必须致电 setOwnerDocument。附加克隆节点时,应自动设置所有者文档。