gpt4 book ai didi

xml - 我如何摆脱 Perl 的 XML::LibXML 模块中 findnodes 返回的不需要的节点?

转载 作者:数据小太阳 更新时间:2023-10-29 02:22:32 28 4
gpt4 key购买 nike

以下只是我正在处理的 XML 的一小部分。我想提取子树下的所有属性、标签名称和文本。

<?xml version='1.0' encoding='UTF-8'?>
<Warehouse>
<Equipment id="ABC001" model="TV" version="3_00">
<attributes>
<Location>Chicago</Location>
<Latitude>30.970</Latitude>
<Longitude>-90.723</Longitude>
</attributes>
</Equipment></Warehouse>

我有这样的编码示例:

#!/usr/bin/perl
use XML::LibXML;
use Data::Dumper;

$parser = XML::LibXML->new();
$Chunk = $parser->parse_file("numone.xml");

@Equipment = $Chunk->findnodes('//Equipment');
foreach $at ($Equipment[0]->getAttributes()) {
($na,$nv) = ($at -> getName(),$at -> getValue());
print "$na => $nv\n";
}

@Equipment = $Chunk->findnodes('//Equipment/attributes');
@Attr = $Equipment[0]->childNodes;
print Dumper(@Attr);

foreach $at (@Attr) {
($na,$nv) = ($at->nodeName, $at->textContent);
print "$na => $nv\n";
}

我得到的结果是这样的:

id => ABC001
model => TV
version => 3_00
$VAR1 = bless( do{\(my $o = 10579528)}, 'XML::LibXML::Text' );
$VAR2 = bless( do{\(my $o = 13643928)}, 'XML::LibXML::Element' );
$VAR3 = bless( do{\(my $o = 13657192)}, 'XML::LibXML::Text' );
$VAR4 = bless( do{\(my $o = 13011432)}, 'XML::LibXML::Element' );
$VAR5 = bless( do{\(my $o = 10579752)}, 'XML::LibXML::Text' );
$VAR6 = bless( do{\(my $o = 10565696)}, 'XML::LibXML::Element' );
$VAR7 = bless( do{\(my $o = 13046400)}, 'XML::LibXML::Text' );
#text =>

Location => Chicago
#text =>

Latitude => 30.970
#text =>

Longitude => -90.723
#text =>

提取属性似乎还可以,但是提取标签名称和文本得到了额外的内容。我的问题是:

  1. 那些 ::Text 元素来自哪里?
  2. 如何摆脱那些多余的元素和#text 东西?

谢谢,

最佳答案

首先你真的应该在程序开始时use strictuse warnings,并在第一次使用时用my 声明所有变量。这将揭示许多简单的错误,并且在您寻求帮助的程序中尤为重要。

如您所知,XML::LibXML::Text 条目是空白文本节点。如果您希望忽略 XML::LibXML 解析器,则在解析器对象上设置 no_blanks 选项。

此外,您最好使用更新的 load_xml 方法,而不是如下所示的过时的 parse_file

my $parser = XML::LibXML->new(no_blanks => 1);
my $Chunk = $parser->load_xml(location => "numone.xml");

程序的这个更改版本的输出看起来像

id => ABC001
model => TV
version => 3_00
$VAR1 = bless( do{\(my $o = 7008120)}, 'XML::LibXML::Element' );
$VAR2 = bless( do{\(my $o = 7008504)}, 'XML::LibXML::Element' );
$VAR3 = bless( do{\(my $o = 7008144)}, 'XML::LibXML::Element' );
Location => Chicago
Latitude => 30.970
Longitude => -90.723

关于xml - 我如何摆脱 Perl 的 XML::LibXML 模块中 findnodes 返回的不需要的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9605801/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com