Xml 如何在Perl中从字符串中提取特定标记之间的数据?

Xml 如何在Perl中从字符串中提取特定标记之间的数据?,xml,perl,substring,Xml,Perl,Substring,例如,从以下字符串 <?xml version="1.0"?><root><point><message>hello world 1</message></point><point><data><message>hello world 2</message></data></point></root> 有没有一个简单的方法可以做到这一点 我

例如,从以下字符串

<?xml version="1.0"?><root><point><message>hello world 1</message></point><point><data><message>hello world 2</message></data></point></root>
有没有一个简单的方法可以做到这一点


我所能想到的就是首先找出和的位置,然后在循环中生成子字符串。有更好的方法吗?

使用XML解析器。在Subs模式下似乎已经足够好了。

使用XML解析器。在Subs模式下似乎已经足够好了。

您的数据不是XML,因此我想您必须使用正则表达式:

perl -n -E'say $1 while m{<message>(.*?)</message>}g' your_file_here.xml 


您的数据不是XML,因此我想您必须为此使用正则表达式:

perl -n -E'say $1 while m{<message>(.*?)</message>}g' your_file_here.xml 

使用XML解析器。我喜欢

使用严格;
使用警告;
使用特征qw(例如);
使用XML::libxmlqw();
my$xml=使用xml解析器。我喜欢

使用严格;
使用警告;
使用特征qw(例如);
使用XML::libxmlqw();

我的$xml=xml::Simple也可用。xml文档中只能有一个根目录,因此xml解析器不会处理此数据。我已经手动创建了xml架构,现在添加了一个根目录。@MatthewWilson:的确如此,但我认为在这个用例中,它不如xml::parser适合。xml::Simple也可用。xml文档中只能有一个根目录,所以XML解析器不会处理这个数据我已经手工创建了XML模式,现在添加了一个根。@MatthewWilson:确实如此,但我认为在这个用例中,它不如XML::parser那么适合。添加了一个根-根以使其成为有效的XML。尽管如此,请保留您的答案,我也会尝试这种方式。谢谢。添加了root-root以使其成为有效的XML。尽管如此,请保留您的答案,我也会尝试这种方式。谢谢
xml_grep --text_only message mes.xml 
xml_grep2 --text_only '//message' mes.xml # xml_grep2 is in App::xml_grep2
perl -MXML::Twig -E'XML::Twig->new( twig_handlers => 
                                      { message => sub { say $_->text; }, })
                             ->parsefile( "mes.xml")'
use strict;
use warnings;
use feature qw( say );

use XML::LibXML qw( );

my $xml = <<'__EOI__';
   <?xml version="1.0"?><root>
   <point><message>hello world 1</message></point>
   <point><data><message>hello world 2</message></data></point>
   </root>
__EOI__

my $parser = XML::LibXML->new();
my $doc    = $parser->parse_string($xml);
my $root   = $doc->documentElement();

say $_->textContent() for $root->findnodes('//message');