从PERL LibXML分析器获取完整的XML字符串 [英] Getting full XML string from PERL LibXML Parser

查看:86
本文介绍了从PERL LibXML分析器获取完整的XML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要处理以下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 ?

推荐答案

XML :: LibXML :: Node对象具有

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_stringas_stringstringify或仅搜索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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆