我正在尝试制作XML文档。特别是,如下
<spirit:component xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4"
xmlns:vendorExtensions="$IREG_GEN/XMLSchema/SPIRIT"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="$IREG_GEN/XMLSchema/SPIRIT/VendorExtensions.xsd
http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4
http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4/index.xsd">
所以我做了一个perl脚本,如下所示
use strict;
use warnings;
use Spreadsheet::ParseXLSX;
use XML::LibXML;
my $doc = XML::LibXML::Document->new('1.0', 'utf-8');
my $root = $doc->createElement('spirit:component');
#$root->appendChild($doc->createComment("JJ"));
$root->setAttribute('xmlns:spirit'=> "http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4");
$root->setAttribute('xmlns:vendorExtensions'=> "$IREG_GEN/XMLSchema/SPIRIT");
$root->setAttribute('xmlns:xsi'=> "http://www.w3.org/2001/XMLSchema-instance");
$root->setAttribute('xsi:schemaLocation'=> "http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4
http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4
http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4/index.xsd");
$doc->setDocumentElement($root);
print $doc->toString(1);
但是问题是我得到了结果
<spirit:component xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4" xmlns:vendorExtensions="$IREG_GEN/XMLSchema/SPIRIT" xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4 											http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4 											http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4/index.xsd"/>
这里有两个问题,	
和index.xsd"/>
我可以删除换行符然后解析为下面的
$root->setAttribute('xsi:schemaLocation'=> "http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4 http://www.spiritconsortium.org/XMLSchema/SPIRIT/1
.4 http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4/index.xsd");
特别是,如何去除index.xsd"/>
中的/
?我用错函数了吗?
在XML中,没有任何子标记或其他封闭内容的标记可以并且通常写成单个空元素形式<foo/>
而不是<foo></foo>
。但它必须是其中之一;与HTML不同,XML中的每个开始标记都需要一个结束标记。所以这部分输出没有问题。
对于xsi:schemaLocation
属性的文本(需要有偶数个元素-它的名称空间和模式URL对)…	
是一个选项卡;用空格替换它们;这些不会被编码。不过,换行符仍然可以。根据对属性文本中换行符是否有效的SO问题的回答,当使用换行符的程序请求内容时,实体将被转换为字符,属性中的所有空白都应由XML解析器转换为空格。因此,虽然它看起来很丑,但在使用符合XML解析器的实践中,您所拥有的应该不会引起问题。
通过管道将脚本的输出输出到下面的测试:
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
use XML::LibXML;
my $dom = XML::LibXML->load_xml({ IO => *STDIN });
my $root = $dom->documentElement();
for my $attr ($root->attributes()) {
say $attr->name(), " is ", $attr->getValue();
}
打印出
schemaLocation is http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4
http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4
http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4/index.xsd
xmlns:spirit is http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4
xmlns:vendorExtensions is $IREG_GEN/XMLSchema/SPIRIT
xmlns:xsi is http://www.w3.org/2001/XMLSchema-instance
所以这似乎是正确的libxml2,至少。