[英]Perl script to parse XML using XML::LibXML;
I think this is a very simple issue, but I cannot figure it out despite many searches. 我认为这是一个非常简单的问题,但尽管进行了大量搜索,但我无法弄明白。
I am trying to parse the following XML to print something similar to TAG=VALUE, so that I can write this to a CSV file. 我试图解析以下XML以打印类似于TAG = VALUE的内容,以便我可以将其写入CSV文件。 The problem is the tags are not always the same for each sample.
问题是每个样本的标签并不总是相同。 I cannot seem to figure out how to get the actual tag names.
我似乎无法弄清楚如何获得实际的标签名称。 Any help appreciated!!!
任何帮助赞赏!
XML File - XML文件 -
<Statistics>
<Stats>
<Sample>
<Name>System1</Name>
<Type>IBM</Type>
<Memory>2GB</Memory>
<StartTime>2012-04-26T14:30:01Z</StartTime>
<EndTime>2012-04-26T14:45:01Z</EndTime>
</Sample>
<Sample>
<Name>System2</Name>
<Type>Intel</Type>
<Disks>2</Disks>
<StartTime>2012-04-26T15:30:01Z</StartTime>
<EndTime>2012-04-26T15:45:01Z</EndTime>
<Video>1</Video>
</Sample>
</Stats>
</Statistics>
Script - 脚本 -
#!/usr/bin/perl
use XML::LibXML;
$filename = "data.xml";
my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file($filename);
for my $sample ($xmldoc->findnodes('/Statistics/Stats/Sample')) {
print $sample->nodeName(), ": ", $sample->textContent(), "\n";
}
You have the right method for getting the tag names, you just need an extra loop to run through the tags inside each <sample>
: 您有正确的方法来获取标记名称,您只需要一个额外的循环来遍历每个
<sample>
的标记:
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $filename = "data.xml";
my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file($filename);
for my $sample ($xmldoc->findnodes('/Statistics/Stats/Sample')) {
for my $property ($sample->findnodes('./*')) {
print $property->nodeName(), ": ", $property->textContent(), "\n";
}
print "\n";
}
Edit : I have now created a tutorial site called Perl XML::LibXML by Example which answers exactly this type of question. 编辑 :我现在已经创建了一个名为Perl XML :: LibXML的教程网站,该网站完全回答了这类问题。
You need to iterate over the children of sample node, 您需要遍历示例节点的子节点,
for my $sample ( $xmldoc->findnodes('/Statistics/Stats/Sample') ) {
print $sample->nodeName(), "\n";
foreach my $child ( $sample->getChildnodes ) {
if ( $child->nodeType() == XML_ELEMENT_NODE ) {
print "\t", $child->nodeName(), ":", $child->textContent(), "\n";
}
}
}
will show, 将会呈现,
Sample
Name:System1
Type:IBM
Memory:2GB
StartTime:2012-04-26T14:30:01Z
EndTime:2012-04-26T14:45:01Z
Sample
Name:System2
Type:Intel
Disks:2
StartTime:2012-04-26T15:30:01Z
EndTime:2012-04-26T15:45:01Z
Video:1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.