How can I add an attribute to a child element using Perl's XML::Twig?

自古美人都是妖i 提交于 2020-01-15 06:08:09

问题


I have an XML string like this:

<DATA>
   <CHILD_DATA ATVAL="value1"/>
   <CHILD_DATA />
</DATA>

The final output I want is:

<DATA>
   <CHILD_DATA ATVAL="value1"/>
   <CHILD_DATA ATVAL="value2"/>
</DATA>

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?


回答1:


As Jon hinted to you, you have a syntax error in the code you posted. You should have seen a compile error like:

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;



回答2:


Just a few thoughts:

  1. Posting the same question multiple times is not going to endear anyone to helping you.

  2. Your code isn't even syntactically correct, so I'm not surprised you're experiencing problems.

  3. Why not include the errors you are getting? Perhaps that might shed some light on the problem?



来源:https://stackoverflow.com/questions/1264506/how-can-i-add-an-attribute-to-a-child-element-using-perls-xmltwig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!