如何使用Perl的XML :: Twig向子元素添加属性? [英] How can I add an attribute to a child element using Perl's XML::Twig?
问题描述
我有一个像这样的XML字符串:
I have an XML string like this:
<DATA>
<CHILD_DATA ATVAL="value1"/>
<CHILD_DATA />
</DATA>
我想要的最终输出是:
<DATA>
<CHILD_DATA ATVAL="value1"/>
<CHILD_DATA ATVAL="value2"/>
</DATA>
我的树枝$t
在<DATA>
.现在,我想向第二个<CHILD_DATA />
添加一个属性.该属性为ATVAL="value2"
.我尝试了以下方法:
My twig $t
is at <DATA>
. Now I want to add an attribute to the second <CHILD_DATA />
. The attribute is ATVAL="value2"
. I tried the following:
$t->last_child('CHILD_DATA')->set_att{"ATVAL","value2"};
这不起作用.此代码有什么问题?还有另一种方法吗?
This didn't work. What's wrong with this code? Is there another way to do this?
推荐答案
正如乔恩向您暗示的那样,您在发布的代码中存在语法错误.您应该已经看到编译错误,例如:
As Jon hinted to you, you have a syntax error in the code you posted. You should have seen a compile error like:
测试行18-> set_att {"附近的语法错误 由于编译错误,program.pl的执行中止了.
syntax error at test line 18, near "->set_att{" Execution of program.pl aborted due to compilation errors.
但是,您可能已在答案中输入了代码,以使代码与您的实际操作不符.始终将实际代码放入您的问题中,而不是重新键入它,并始终在可能的情况下发布完整的程序.当您发布程序时,我不必从头开始调试我认为您可能正在做的事情. :)
However, you might have typed the code into your answer so that code doesn't match what you are actually doing. Always put the actual code into your question rather than re-typing it, and always post a full program when you can. When you post your program, I don't have to start from scratch to debug what I think you might be doing. :)
这是一个满足您需求的程序:
Here's a program that does what you want:
#!/usr/bin/perl
use XML::Twig;
my $xml = <<'XML';
<DATA>
<CHILD_DATA ATVAL="value1"/>
<CHILD_DATA />
</DATA>
XML
my $twig= XML::Twig->new( keep_spaces => 1 );
$twig->parse( $xml );
$t = $twig->root;
$t->last_child('CHILD_DATA')->set_att("ATVAL" => "value2");
$twig->flush;
这篇关于如何使用Perl的XML :: Twig向子元素添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!