1

我正在尝试在<value></value>,之间附加一个字符串

<?xml version="1.0" encoding="UTF-8"?>
<rs:alarm-request throttlesize="100" xmlns:rs="http://url.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.url.com">
    <rs:attribute-filter>
    <search-criteria xmlns="http://www.url">
    <filtered-models>
      <equals>
        <attribute id="0x1144f50">
        <value></value>
        </attribute>
      </equals>
      </filtered-models>
    </search-criteria>
  </rs:attribute-filter>
    <!-- Models of Interest -->
    <rs:target-models>
    </rs:target-models>
</rs:alarm-request>

我使用了以下代码,但我不断收到:无法通过包“XML::LibXML::NodeList”定位对象方法“appendTextNode”

my $parser     = XML::LibXML->new();

# Insert devices MH to GETdevices_xmlbody template
my $doc = $parser->parse_file($current_working_dir.'\GETdevices_xmlbody.xml');
my $elem = $doc->findnodes('//rs:attribute-filter/search-criteria/filtered-models/equals/attribute/value');

# $elem->removeChildNodes();
$elem->appendTextNode('STRING');
4

2 回答 2

4

你也可以使用XML::Twig

内容script.pl

#!/usr/bin/env perl

use warnings;
use strict;
use XML::Twig;

my $twig = XML::Twig->new(
    twig_handlers => {
        '//rs:attribute-filter/search-criteria/filtered-models/equals/attribute/value' => sub {
            $_->set_text('STRING');
        },  
    },  
    pretty_print => 'indented',
)->parsefile( shift )->print;

像这样运行它:

perl script.pl xmlfile

这会产生:

<?xml version="1.0" encoding="UTF-8"?>
<rs:alarm-request throttlesize="100" xmlns:rs="http://url.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.url.com">
  <rs:attribute-filter>
    <search-criteria xmlns="http://www.url">
      <filtered-models>
        <equals>
          <attribute id="0x1144f50">
            <value>STRING</value>
          </attribute>
        </equals>
      </filtered-models>
    </search-criteria>
  </rs:attribute-filter>
  <!-- Models of Interest --> 
  <rs:target-models></rs:target-models>
</rs:alarm-request>
于 2013-09-26T20:28:59.010 回答
3

您要求获取所有符合您的条件的节点。你需要遍历它们。

my $elems = $doc->findnodes('...');
for my $elem ($elems->get_nodelist) {
   ...
}

更简单:

my @elems = $doc->findnodes('...');
for my $elem (@elems) {
   ...
}

如果你只是期待一个,你可以抓住第一个。

my ($elem) = $doc->findnodes('...');
于 2013-09-26T20:23:44.093 回答