【问题标题】:XML::Compile does not find the root element I give itXML::Compile 没有找到我给它的根元素
【发布时间】:2014-07-04 10:33:05
【问题描述】:

目标:使用现有 XSD 架构生成填充和写入 XML 输出所需的 Perl 数据结构。

我做了什么:我安装了XML::Compile,找到了如何使用它的教程,并在此处阅读了修改后的示例。我已经使用 CAM 模板编辑器处理了我的 XSD 文件,以确保 CAM 可以从模板生成示例 XML 文件,并且我已经将 XML 输出与 XSD 进行了比较,以确保两者以我认为应该的方式相关.他们有。

接下来,我只是将XML::Compile::Schema 指向 XSD 文件,然后要求创建模板字符串,要求 template() 从 XSD 中指定的根元素开始。

出了什么问题:“错误:找不到元素或属性‘[root_element_name]’

我的 XSD 确实与我在找到的示例中看到的不同。这是我所拥有的:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"

<xs:annotation></xs:annotation>

<!-- Include XML Schema containing type definitions and data validation -->
  <xs:include id="DataDefinitions" schemaLocation="DataDefinitions_XMLSchema.xsd"></xs:include>

  <!-- Root element -->
  <xs:element name="Metrics" type="metrics"></xs:element>

  <xs:complexType name ="metrics">
    <xs:sequence minOccurs ="1" maxOccurs ="1">
      <xs:element name = ...></xs:element>
      .
      .
      <xs:element name = ....></xs:element>
    </xs:sequence>
  </xs:complexType>

  [other complexType definitions used above to type some of the elements in the complexType 'metrics']

</xs:schema>

上面的几个元素都有类型,然后在我展示的部分下面定义,这就是 XSD 的本质。我在这里清楚地遗漏了很多细节,但我认为(“希望”)这与问题无关。

Perl 非常简单,即使是错误的:

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

my $xsd = 'C:\schema.xsd';
my $schema = XML::Compile::Schema=>new($xsd);
my $xml_template = $schema->template('PERL', 'Metrics');

失败并出现上述错误:

error: cannot find element or attribute named 'Metrics'

认为我可能不明白什么时候需要命名空间限定,什么时候不需要,我限定了 Metrics 并调用了

my $xml_template = $schema->template('PERL', 'mstns:Metrics');

同样的失败。

我见过的定义根元素的其他示例是这样完成的:

<element name = "Metrics">
  <complexType>
    <sequence>
      [etc]
    </sequence>
  </complexType>
</element>

而不是这样做的方式,我想知道问题是否是 XML::Compile 无法识别的允许样式的某些更改。我只是不知道如何确定为什么 template() 找不到我指定的元素。

建议?

【问题讨论】:

    标签: xml perl xsd perl-module


    【解决方案1】:

    在你的template 调用中用花括号指定targetNamespace 作为类型...像这样:

    use warnings;
    use strict;
    use XML::LibXML;
    use XML::Compile;
    
    my $xsd = 'C:\schema.xsd';
    my $schema = XML::Compile::Schema=>new($xsd);
    my $xml_template = $schema->template('PERL', '{http://tempuri.org/XMLSchema.xsd}Metrics');
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多