【问题标题】:How do I write character ALT-0146 to an XML file using Perl?如何使用 Perl 将字符 ALT-0146 写入 XML 文件?
【发布时间】:2011-05-27 06:00:49
【问题描述】:

这就是字符,我找不到检测、替换或将其正确写入 XML 文件的方法。起初我使用字符串连接,然后我明智地使用 XML::Writer,但它仍然无法工作,之后 XML 仍然被破坏。(需要 UTF-8 格式)

这是我写的一个测试仍然失败:

    my $output = new IO::File(">$foundFilePath");
    my $writer = new XML::Writer(OUTPUT => $output);
    $writer->xmlDecl("UTF-8");
    $writer->startTag("xml");
    $writer->startTag("test");
    $writer->characters("’");
    $writer->endTag("test");
    $writer->endTag("xml");
    $writer->end();
    $output->close();

更具体地说,我正在尝试从此页面获取数据:http://investing.businessweek.com/businessweek/research/stocks/private/snapshot.asp?privcapId=4439466

William O'Keefe 先生把一切都搞砸了。

【问题讨论】:

    标签: html xml windows perl utf-8


    【解决方案1】:

    您需要做两件事。如果你想将 UTF-8 写入文件,你需要这样说:

    my $output = IO::File->new($foundFilePath, ">:utf8");
    

    如果你想在你的源代码中使用文字 UTF-8 字符串,你需要说

    use utf8;
    

    在程序的开头。否则,Perl 假定您的源代码是 Latin-1。

    这是一个完整的示例脚本:

    use utf8;
    use strict;
    use warnings;
    use IO::File;
    use XML::Writer;
    
    my $foundFilePath = 'test.xml';
    my $output = IO::File->new($foundFilePath, ">:utf8");
    my $writer = XML::Writer->new(OUTPUT => $output);
    $writer->xmlDecl("UTF-8");
    $writer->startTag("xml");
    $writer->startTag("test");
    $writer->characters("’");
    $writer->endTag("test");
    $writer->endTag("xml");
    $writer->end();
    $output->close();
    

    【讨论】:

    • 另外,$writer->characters(chr(0x2019));$writer->characters("\x{2019}"); 不太可能被编辑破坏。
    • 这有助于创建角色,但我遇到的主要问题是首先检测到它,我如何才能真正用正则表达式捕捉角色?
    • 虽然说真的,如果你的所有输入和输出都使用 utf8,则无需检测它——一切都会正常工作。
    • @Sho,这是一个单独的问题。如果您需要答案,请将其作为一个新问题提出(包含有关您尝试过的更多详细信息)。
    • 我尝试了不止几种不同的表达方式,但都没有出现任何结果。我可能已经保存并读取了一个意外在 latin-1 中的 html 文件......你能看看这个文件,看看我陷入了什么样的编码噩梦? filevo.com/wkkixmebxlmh.html
    猜你喜欢
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多