从PERL LibXML分析器获取完整的XML字符串 [英] Getting full XML string from PERL LibXML Parser
问题描述
我要处理以下XML
<table>
<col1>check1</col1>
<col2>check2</col2>
<col3>check3</col3>
<content>
<data>gt1</data>
<data>check_gt1</data>
</content>
</table>
我想从解析器中获取"<content><data>gt1</data><data>check_gt1</data></content>
".
I want to get "<content><data>gt1</data><data>check_gt1</data></content>
" from the parser.
我的解析代码如下,
my $parser = XML::LibXML->new();
my $respDom = $parser->parse_string($xmldata);
print "content is ".$respDom->getDocumentElement->findnodes("//content");
上面的代码在节点内部生成textContent.如何获取上面提到的数据?
The above code results in the textContent inside the nodes.How can I get the data I mentioned above ?
推荐答案
The XML::LibXML::Node objects have a method toString
. That's what you need. I found it with a quick search of the XML::LibXML documentation.
use strict;
use warnings;
use XML::LibXML;
my $xmldata = <<'XML';
<table>
<col1>check1</col1>
<col2>check2</col2>
<col3>check3</col3>
<content>
<data>gt1</data>
<data>check_gt1</data>
</content>
</table>
XML
my $parser = XML::LibXML->new();
my $respDom = $parser->parse_string($xmldata);
print "content is "
. $respDom->getDocumentElement->findnodes("//content")->[0]->toString;
这将打印:
content is <content>
<data>gt1</data>
<data>check_gt1</data>
</content>
通常,如果我需要类似的内容并且不确定在特定模块中的工作方式,我总是搜索to_string
,as_string
,stringify
或仅搜索string
.几乎总是其中之一.
In general, I always search for either to_string
, as_string
, stringify
or simply string
if I need something like that and am not sure how that works in a specific module. It's almost always one of those.
更新
要仅获取<content>
元素的内部XML,必须获取其子节点并对每个子节点执行toString
. map
整个事物需要在 list上下文中调用,否则将引发错误.请注意如何在print
语句中将.
更改为,
.
To only get the inside XML of the <content>
element, you have to grab its child nodes and do toString
for each of them. The map
whole thing needs to be called in list context, or it will throw an error. Note how I changed the .
to a ,
in the print
statement.
print "content is "
, $respDom->getDocumentElement->findnodes("//content")->[0]->childNodes->map(sub {$_->toString});
这篇关于从PERL LibXML分析器获取完整的XML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!