【问题标题】:Is it possible for XML::LibXML to parse quirky tags?XML::LibXML 是否可以解析古怪的标签?
【发布时间】:2012-10-10 13:05:40
【问题描述】:

是否可以让XML::LibXML 解析下例所示的节点?我意识到我可能通过将 '*' 指定为节点名称的一部分来创建无效的 XML,如果有人能解释为什么它无效,我将不胜感激:

use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML->createDocument;

my $quirky = XML::LibXML::Element->new( 'YAK*' );
$quirky->appendText( 'Important Data' );

$doc->setDocumentElement( $quirky );

print $doc->toString;  # <?xml version="1.0"?>
                       # <YAK*>Important Data</YAK*>

my $data = XML::LibXML
           ->new
             ->parse_string( $doc->toString );

输出:

<?xml version="1.0"?>
<YAK*>Important Data</YAK*>
:2: parser error : error parsing attribute name
<YAK*>Important Data</YAK*>
    ^
:2: parser error : attributes construct error
<YAK*>Important Data</YAK*>
    ^
:2: parser error : Couldn't find end of Start Tag YAK line 2
<YAK*>Important Data</YAK*>
    ^
:2: parser error : Extra content at the end of the document
<YAK*>Important Data</YAK*>
    ^

【问题讨论】:

    标签: perl xml-libxml


    【解决方案1】:

    如果您打开recover 选项,它将尝试工作–

    my $parser = XML::LibXML->new;
    $parser->recover_silently(1);
    my $doc2 = $parser->parse_string( $doc->toString );
    print $doc2->toString;
    

    但是,如您所见,虽然它可以解析无效文档,但它不能/不会往返一次——

    <?xml version="1.0"?>
    <YAK/>
    

    【讨论】:

      【解决方案2】:

      * 不是元素名称中的有效字符,因为规范不允许这样的字符出现在元素名称中。见NameChar

      【讨论】:

      • 我明白了...所以用XML::LibXML 解析这个几乎是不可能的吗?
      • @Zaid,正确。 libxml 是一个验证解析器。您必须使用一些 s/// 或其他东西来预处理 XML。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多