perl 如何通过XML::LibXML添加子和孙XML标签?

mwngjboj  于 2022-11-15  发布在  Perl
关注(0)|答案(1)|浏览(164)

我尝试创建一个简单的XML文件,并通过XML::LibXML添加ChildGrandchild XML标记。
我制作了countrylocation标签,如下所示,但我想在countrylocation标签下添加子标签和孙标签,如<dev>value</dev>。如何通过XML::LibXML添加子XML标签和孙XML标签?

use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0', 'utf-8');
#my $record = $doc->documentElement;
my $root = $doc->createElement('my-root-element');
$root->setAttribute('some-attr'=> 'some-value');

my $country = $doc->createElement('country');
$country-> appendText('Jamaica');
$root->appendChild($country);

    
my $dev = $doc->createElement('dev');
$dev-> appendText('value');
$country->appendChild($dev);

my $location = $doc->createElement('location');
$location-> appendText('21.241.21.2');
$root->appendChild($location);

$doc->setDocumentElement($root);
print $doc->toString(1);

我得到的结果如下:

<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value">
  <country>Jamaica<dev>value</dev></country>
  <location>21.241.21.2</location>
</my-root-element>

实际上,我期望的输出如下

<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value">
  <country>
        <dev>
             <Name>Jameica</Name>
             <field>value</field>
             <range>value1</range>
        </dev>
  </country>
  <country>
        <dev>
             <Name>USA</Name>
             <field>value</field>
             <range>value1</range>
        </dev>
   </country>
</my-root-element>
dsekswqp

dsekswqp1#

由于<country>只有元素,没有文本,因此不应使用$country->appendText('Jamaica');。同样,不应将appendText用于<dev>
您还需要在<dev>下创建3个子元素:Namefieldrange。对于这些,您需要调用$dev->appendChild等。
这段代码为您设置了一条获得所需输出类型的路径:

use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0', 'utf-8');
my $root = $doc->createElement('my-root-element');
$root->setAttribute('some-attr'=> 'some-value');

my $country = $doc->createElement('country');
$root->appendChild($country);
    
my $dev = $doc->createElement('dev');
$country->appendChild($dev);

my $name = $doc->createElement('Name');
$name->appendText('Jamaica');
$dev->appendChild($name);

my $field = $doc->createElement('field');
$field->appendText('value');
$dev->appendChild($field);

my $range = $doc->createElement('range');
$range->appendText('value1');
$dev->appendChild($range);

$doc->setDocumentElement($root);
print $doc->toString(1);

印刷品:

<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value">
  <country>
    <dev>
      <Name>Jamaica</Name>
      <field>value</field>
      <range>value1</range>
    </dev>
  </country>
</my-root-element>

相关问题