我是XML世界的新手。我编写了以下代码来使用XML :: LibXML生成XML。我理解我似乎将命名空间视为属性,我觉得这是不正确的。我不知道该怎么做。所以寻求你的帮助,请纠正我的代码。
XML文档:
<RootDocument protocol="OCI" xmlns="C" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<sessionId xmlns="">172.24.160.8,31436753,1298637565495</sessionId>
<command xsi:type="AuthenticationRequest" xmlns="">
<userId>automation</userId>
</command>
</RootDocument>
Perl脚本:
my $ociRequest = XML::LibXML::Document->new( '1.0', 'utf-8' );
my $root = $ociRequest->createElement ('RootDocument');
$root->addChild ($ociRequest->createAttribute ( protocol => 'OCI' ) );
$root->addChild ($ociRequest->createAttribute ( xmlns => 'C' ) );
$root->addChild ($ociRequest->createAttribute ( 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' ) );
#$root->setNamespace ('http://www.w3.org/2001/XMLSchema-instance', 'xsi', 0);
$ociRequest->setDocumentElement ($root);
my $session = $ociRequest->createElement ('sessionId');
$session->addChild ($ociRequest->createAttribute ( xmlns => '') );
$session->addChild($ociRequest->createTextNode($sessionID));
$root->addChild($session);
my $command = $ociRequest->createElement ('command');
$command->addChild ($ociRequest->createAttribute ( 'xsi:type' => 'AuthenticationRequest' ) );
$command->addChild ($ociRequest->createAttribute ( 'xmlns' => '' ) );
my $userid = $ociRequest->createElement ('userId');
$userid->addChild($ociRequest->createTextNode('automation'));
$command->addChild($userid);
$root->addChild ($command);
$ociRequest->setDocumentElement($root);
my $xml = $ociRequest->toString;
答案 0 :(得分:5)
来自Perldoc:
$element = $dom->createElementNS( $namespaceURI, $qname );
您需要在创建元素时指定命名空间。