如何正确调整节点的XML层次结构

时间:2015-06-04 07:17:46

标签: php html dom

我想使用html表单创建一个xml文件。我能够创建一个xml文件......但是当时有些hirarchy出现了错误。请检查我的代码或更新它。下面是我想要的输出。

output :-<url>TODO</url>
    <licenses>
        <license>
            <name>TODO</name>
            <connection>TODO</connection>
        </license>
    </licenses>

php代码: -

$text5 = htmlentities($_POST['tb5']);
$text6 = htmlentities($_POST['tb6']);
$text7 = htmlentities($_POST['tb7']);


$xmlns = 'http://maven.apache.org/POM/4.0';
$document = new DOMDocument();
$project = $document
  ->appendChild($document->createElementNS($xmlns, 'project'));
$project->setAttributeNS(
  
  'http://www.w3.org/2001/XMLSchema-instance',  
  'xsi:schemaLocation',
  'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'
);

$project
  ->appendChild($document->createElementNS($xmlns, 'url'))
  ->appendChild($document->createTextNode($text5));


$project
  ->appendChild($document->createElementNS($xmlns, 'licenses')) 
  ->appendChild($document->createElementNS($xmlns, 'license')) 
  ->appendChild($document->createElementNS($xmlns, 'url')) 
  ->appendChild($document->createTextNode($text6));
   ->appendChild($document->createElementNS($xmlns, 'name')) 
  ->appendChild($document->createTextNode($text7));
 

$document->save("d.xml");

?>

1 个答案:

答案 0 :(得分:0)

在创建文本节点后,代码中存在语法错误,并且需要对DOM层次结构进行语义更改。这是纠正的代码,将appendChild更正为$ project。

<?php

$text5 = htmlentities($_POST['tb5']);
$text6 = htmlentities($_POST['tb6']);
$text7 = htmlentities($_POST['tb7']);

$xmlns = 'http://maven.apache.org/POM/4.0';
$document = new DOMDocument();
$project = $document
  ->appendChild($document->createElementNS($xmlns, 'project'));
$project->setAttributeNS(

  'http://www.w3.org/2001/XMLSchema-instance',
  'xsi:schemaLocation',
  'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'
);

$project
  ->appendChild($document->createElementNS($xmlns, 'url'))
  ->appendChild($document->createTextNode($text5));


$license = $project
  ->appendChild($document->createElementNS($xmlns, 'licenses'))
  ->appendChild($document->createElementNS($xmlns, 'license')) ;

$license
  ->appendChild($document->createElementNS($xmlns, 'name'))
  ->appendChild($document->createTextNode($text6));

$license
  ->appendChild($document->createElementNS($xmlns, 'connection'))
  ->appendChild($document->createTextNode($text7));

$document->save("d.xml");

?>

编辑:我稍微修改了脚本以匹配指定的XML输出格式。您正在创建第二个url节点,但没有创建正确的名称/连接节点。现在已经到位了。