Xml twig:在混合内容中查找位于子元素之前的子字符串
我正在处理一个包含一些混合内容的XML文件(元素包含文本、一个子标记,然后是文本)。Xml twig:在混合内容中查找位于子元素之前的子字符串,xml,perl,xml-twig,Xml,Perl,Xml Twig,我正在处理一个包含一些混合内容的XML文件(元素包含文本、一个子标记,然后是文本)。 我想为每个父元素提取子元素前面的单词(substring) XML输入示例: 我知道,仅将text\u应用于父元素会给我它周围都是文本,因此我不必再处理子元素,但我不知道如何定位前面的单词 我是否应该用某种文本标记(如|)替换子元素并将剩余的文本作为单个字符串遍历 我不是要一个完整的“现成的”答案,但是一些说明肯定会有帮助。您可以找到每个子元素,然后检查其左边兄弟元素的文本。那是以前的兄弟姐妹。这很方便,因为前
我想为每个父元素提取子元素前面的单词(substring) XML输入示例: 我知道,仅将
text\u
应用于父元素
会给我它周围都是文本
,因此我不必再处理子元素,但我不知道如何定位前面的单词
我是否应该用某种文本标记(如|
)替换子元素
并将剩余的文本作为单个字符串遍历
我不是要一个完整的“现成的”答案,但是一些说明肯定会有帮助。您可以找到每个
子元素,然后检查其左边兄弟元素的文本。那是以前的兄弟姐妹。这很方便,因为前一个同级节点无论如何都是文本节点。从这里开始,只需找到最后一个词
use strict;
use warnings;
use feature 'say';
use XML::Twig;
my $twig = XML::Twig->new(
TwigHandlers => {
child => sub {
say +( split /\s/, $_->prev_sibling_text )[-1];
},
}
);
$twig->parse( \*DATA );
__DATA__
<root>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
</root>
使用严格;
使用警告;
使用特征“说”;
使用XML::Twig;
my$twig=XML::twig->new(
TwigHandlers=>{
子项=>sub{
say+(拆分/\s/,$->prev\u sibling\u text)[-1];
},
}
);
$twig->parse(\*数据);
__资料__
有文字围绕着它
有文字围绕着它
有文字围绕着它
有文字围绕着它
您可以找到每个子元素
元素,然后在左侧检查其同级元素的文本。那是以前的兄弟姐妹。这很方便,因为前一个同级节点无论如何都是文本节点。从这里开始,只需找到最后一个词
use strict;
use warnings;
use feature 'say';
use XML::Twig;
my $twig = XML::Twig->new(
TwigHandlers => {
child => sub {
say +( split /\s/, $_->prev_sibling_text )[-1];
},
}
);
$twig->parse( \*DATA );
__DATA__
<root>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
</root>
使用严格;
使用警告;
使用特征“说”;
使用XML::Twig;
my$twig=XML::twig->new(
TwigHandlers=>{
子项=>sub{
say+(拆分/\s/,$->prev\u sibling\u text)[-1];
},
}
);
$twig->parse(\*数据);
__资料__
有文字围绕着它
有文字围绕着它
有文字围绕着它
有文字围绕着它
这与@toolic有什么关系?肯定不一样。这与@toolic有什么关系?这肯定不一样。非常感谢,我没有意识到混合内容中的文本可以被视为元素而不是字符串!每段文本都是一个节点。在本例中,您有父节点:(文本节点,子节点:(文本节点),文本节点)
。获取parent
中的所有文本是一个特殊的功能。非常感谢,我没有意识到混合内容中的文本可以被视为元素而不是字符串!每段文本都是一个节点。在本例中,您有父节点:(文本节点,子节点:(文本节点),文本节点)。获取parent
中的所有文本是一项特殊功能。
use strict;
use warnings;
use feature 'say';
use XML::Twig;
my $twig = XML::Twig->new(
TwigHandlers => {
child => sub {
say +( split /\s/, $_->prev_sibling_text )[-1];
},
}
);
$twig->parse( \*DATA );
__DATA__
<root>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
<parent> there is text all <child>text</child> around it</parent>
</root>