如何使用Perl修改XML文件,在XML文件中没有某些节点的开始和结束标记

时间:2022-05-12 06:34:34

For Example the XML file is like

例如,XML文件就像

<ROOT> 
  <TESTING DUMMY="FALSE" NAME="SYSTEM"/> 
  <TESTING DUMMY="FALSE" NAME="SYSTEM1"> 
    <INSTANCE> 
      <PHY FREQ="1000"/> 
    </INSTANCE> 
  </TESTING> 
</ROOT> 

Here in the XML file I want to update the FREQ value and save the file in different name. How to do that?

在XML文件中,我想更新FREQ值并以不同的名称保存文件。怎么做?

2 个解决方案

#1


You can use XML::XSH2, a wrapper around XML::LibXML:

您可以使用XML :: XSH2,XML :: LibXML的包装器:

open file.xml ;
set /ROOT/TESTING[INSTANCE]/INSTANCE/PHY/@FREQ 42 ;
save :f newname.xml ;

#2


In your example - your FREQ tag does have a start and end. That's what the trailing / means. This is one of the reasons why parsing XML with a parser is important. It's a unary tag.

在您的示例中 - 您的FREQ标记确实有一个开始和结束。这就是尾随/意味着什么。这是使用解析器解析XML很重要的原因之一。这是一个一元的标签。

#!/usr/bin/perl
use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> new ( pretty_print => 'indented' ) -> parsefile ( 'my.xml' );
$twig -> get_xpath('TESTING/INSTANCE/PHY',0) -> set_att('FREQ', 300);
$twig -> print;

(For printing to a file, you probably want open and $twig -> sprint);

(对于打印到文件,你可能想要打开和$ twig - > sprint);

#1


You can use XML::XSH2, a wrapper around XML::LibXML:

您可以使用XML :: XSH2,XML :: LibXML的包装器:

open file.xml ;
set /ROOT/TESTING[INSTANCE]/INSTANCE/PHY/@FREQ 42 ;
save :f newname.xml ;

#2


In your example - your FREQ tag does have a start and end. That's what the trailing / means. This is one of the reasons why parsing XML with a parser is important. It's a unary tag.

在您的示例中 - 您的FREQ标记确实有一个开始和结束。这就是尾随/意味着什么。这是使用解析器解析XML很重要的原因之一。这是一个一元的标签。

#!/usr/bin/perl
use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> new ( pretty_print => 'indented' ) -> parsefile ( 'my.xml' );
$twig -> get_xpath('TESTING/INSTANCE/PHY',0) -> set_att('FREQ', 300);
$twig -> print;

(For printing to a file, you probably want open and $twig -> sprint);

(对于打印到文件,你可能想要打开和$ twig - > sprint);