我正在尝试为每个 <>
添加换行符XML::LibXML
的 XML 输出中的行
来自 https://stackoverflow.com/a/2934794/19508169 .
use strict;
use warnings;
use XML::LibXML;
my $doc = XML::LibXML::Document->new('1.0', 'utf-8');
my $root = $doc->createElement('my-root-element');
$root->setAttribute('some-attr'=> 'some-value');
my %elements = (
color => 'blue',
metal => 'steel',
);
for my $name (keys %elements) {
my $tag = $doc->createElement($name);
my $value = $elements{$name};
$tag->appendTextNode($value);
$root->appendChild($tag);
}
$doc->setDocumentElement($root);
print $doc->toString();
但是,当我尝试这段代码时,我得到了没有换行符的结果:
%> perl test2.pl
<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value"><color>blue</color><metal>steel</metal></my-root-element>
我预期如下:
<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value">
<color>blue</color>
<metal>steel</metal>
</my-root-element>
如何为每个 XML 输出添加换行符?
如果加上" \n"
进入print $doc->toString();
作为print $doc->toString(), " \n";
, 它不起作用。
最佳答案
使用 $doc->toString(1)
而不是 $doc->toString()
。
可以说,找到正确的文档并不容易,因为 cpan page of XML::LibXML仅包含指向其他页面的链接。不过,您可以执行 print ref $doc
,它会打印 XML::LibXML::Document
:您现在知道需要查看 the documentation of XML::LibXML::Document .在那里,您会找到 toString
的文档:
$docstring = $dom->toString($format);
[...]
If $format is 1, libxml2 will add ignorable white spaces, so the nodes content is easier to read.
[...]
https://stackoverflow.com/questions/72968364/