myxmlwriter.pm

来自「利用lwp::get写的」· PM 代码 · 共 105 行

PM
105
字号
#!/usr/bin/perl -w
use strict;

#########################
# MyXMLWriter Package
# Yeni, 2006/11
# yeni@yueds.com
#########################
# This script is a part of UCPro project.
# For more information, please visit http://tuc.cn/pro/

# a simplified XML writer.
#
# open -
#   create a XML file and get ready to be written.
#
# close -
#   flush the write buffer, close the file.
#
# start -
#   write a start tag.
#
# end -
#   write a end tag.
#
# put -
#   put a string into XML, the string will be tiny() ed.
#
# start_put_end -
#   a shortcut to put some text in a tag.
#
# tiny -
#   do some clean work to a string, including transforming html escaping char
#   and triming.
#
# trim -
#   remove useless whitespaces before and after the string.

package MyXMLWriter;

use IO::File;
use XML::Writer;    # XML Writer for writing result to XML

my $output;
my $xmlwriter;

sub open {
    my ($output_path) = @_;
    $output = new IO::File(">$output_path");
    $xmlwriter = new XML::Writer(OUTPUT => $output);
}

sub start($) {
    my $tagname = shift;
    $xmlwriter->startTag($tagname);
}

sub end($) {
    my $tagname = shift;
    $xmlwriter->endTag($tagname);
}

sub put($) {
    my $string = shift;
    $xmlwriter->characters(tiny($string));
}

sub start_put_end {
    my($string, $tagname) = @_;
    $xmlwriter->startTag($tagname);
    $xmlwriter->characters(tiny($string));
    $xmlwriter->endTag($tagname);
}

sub close {
    $xmlwriter->end();
    $output->close();
}

# remove html tags and whitespaces
sub tiny($) {
    my $string = shift;
    if(defined $string) {
        $string =~ s/<.+?>//isg;
        $string =~ s/\&nbsp\;/ /isg;
        $string =~ s/\&gt\;/>/isg;
        $string =~ s/\&lt\;/</isg;
        $string =~ s/\&amp\;/&/isg;
        $string =~ s/^\s+//;
        $string =~ s/\s+$//;
        return $string;
    } else {
        return "";
    }
}

# Perl trim function to remove whitespace from the start and end of the string
sub trim($) {
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

1;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?