load_xml(IO => $fh); # create a n-6ren">
gpt4 book ai didi

xml - 按原样使用 XML::LibXML appendTextNode() 追加 CDATA

转载 作者:数据小太阳 更新时间:2023-10-29 01:56:29 29 4
gpt4 key购买 nike

我使用此代码创建一个具有预期输出的新节点:

<item desc="desc foobar"><![CDATA[qux]]></item>

代码:

open my $fh, "<", $xml_file;
binmode $fh;
my $parser = XML::LibXML->new();
my $doc = $parser->load_xml(IO => $fh);

# create a new node in XML file
my $root = $doc->getDocumentElement();
my $new_element = $doc->createElement("item");
# FIXME
$new_element->appendTextNode(sprintf '<![CDATA[%s]]>', join "\n", @input);
$new_element->setAttribute('desc', $desc);
$root->appendChild($new_element);

close $fh;

open my $out, '>', $xml_file;
binmode $out;
$doc->toFH($out);

close $out;

创建新元素文本效果很好,但我想知道如何在没有 XML 实体替换的情况下添加 CDATA:我得到:

<item desc="dddd">&lt;![CDATA[qux]]>
# ^^^^

最佳答案

显然 appendTextNode() 会自动转义文本节点中有问题的字符。这是你应该做的:

my $cdata_node = XML::LibXML::CDATASection->new(
join "\n", @input
);

$new_element->appendChild($cdata_node);

XML::LibXML::CDATASection

 $node = XML::LibXML::CDATASection->new( $content );

The constructor is the only provided function for this package. It is required, because libxml2 treats the different text node types slightly differently.

The class inherits from XML::LibXML::Node

http://search.cpan.org/dist/XML-LibXML/lib/XML/LibXML/CDATASection.pod

XML::LibXML::节点

$childnode = $node->appendChild( $childnode );

The function will add the $childnode to the end of $node's children...

http://search.cpan.org/~shlomif/XML-LibXML-2.0117/lib/XML/LibXML/Node.pod

关于xml - 按原样使用 XML::LibXML appendTextNode() 追加 CDATA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672543/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com