使用 libxml 和 XSD 文件在 Perl 中验证 XML

发布于 2024-09-12 07:31:26 字数 985 浏览 1 评论 0 原文

我试图让我的 perl 脚本从网上获取 Xxml 文件并根据 XSD 文件对其进行验证。

执行此操作的代码如下:

my $url = shift @ARGV;
my $response = $ua->get($url) || die "Can't fetch file";
my $file = $response->content;

my $schema_file = "schema.xsd";
my $schema = XML::LibXML::Schema->new(location => $schema_file);
my $parser = XML::LibXML->new;
my $doc    = $parser->parse_string($file);
eval { $schema->validate($doc) };
die $@ if $@;

运行此结果会导致一个神秘错误:“元素作物数据内容检查失败”(作物数据是我的第一个非根标签)。

在我的 XSD 文件中,条目如下所示:

<xs:element name="cropdata">
<xs:complexType>
<xs:sequence>

然后是一堆“>” 然后:

</xs:sequence>
</xs:complexType>
</xs:element>

进入 perl 调试器显示,在运行 "my $doc = $parser->parse_string($file);" 行后,$doc 打印为 XML::LibXML::文档=标量(0x6b99f0)。

谁能帮助我阐明我做错了什么? (警告:这可能是一个愚蠢的错误,我不会把它过去)。

I am trying to have my perl script get an Xxml file from online and validate it according to an XSD file.

The code to do this is as follows:

my $url = shift @ARGV;
my $response = $ua->get($url) || die "Can't fetch file";
my $file = $response->content;

my $schema_file = "schema.xsd";
my $schema = XML::LibXML::Schema->new(location => $schema_file);
my $parser = XML::LibXML->new;
my $doc    = $parser->parse_string($file);
eval { $schema->validate($doc) };
die $@ if $@;

Running this results in a cryptic error: "Element cropdata content check failure" (cropdata is the first of my nonroot tags).

In my XSD file, the entry looks like:

<xs:element name="cropdata">
<xs:complexType>
<xs:sequence>

Then a bunch of "<xs:element..../>"
and then:

</xs:sequence>
</xs:complexType>
</xs:element>

Going into the perl debugger shows that after letting the line "my $doc = $parser->parse_string($file);" run, $doc prints as XML::LibXML::Document=SCALAR(0x6b99f0).

Can anyone help me shed light on what I am doing wrong? (Warning: it may be a dumb mistake, I wouldn't put it past myself).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潇烟暮雨 2024-09-19 07:31:26

事实证明,我提供的示例 xml 文件无效,您瞧,在 xmllint 中检查并更正它后,一切正常。

Turns out that the sample xml file I had been provided was invalid, and lo and behold, upon checking and correcting it in xmllint, everything works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文