将Xml附加到Php中的儿童元素子元素中

时间:2013-10-10 08:38:12

标签: php xml

我有Xml文件

<user>
<prop name="A">
<sub name="X">
</sub>
</prop>
<prop name="B">
<sub name="Y">
</sub>
</prop>
</user>

我想将$Xml=<design name="J" path="folder"></design>'添加到子名称=“Y”中。 所以它必须像。

<user>
<prop name="A">
<sub name="X">
</sub>
</prop>
<prop name="B">
<sub name="Y">
<design name="J" path="folder"></design>
</sub>
</prop>
</user>

如何在php中使用DOMDocument?

1 个答案:

答案 0 :(得分:0)

您可以使用DomXPath执行此操作,并查询具有特定属性值的<sub>元素,例如//sub[@name="Y"]

示例http://3v4l.org/VQv5k

$data = '<user><prop name="A"><sub name="X"></sub></prop><prop name="B"><sub name="Y"></sub></prop></user>';
$xml = new DomDocument;
$xml->loadXML($data);

//create a xpath instance
$xpath = new DomXpath($xml);

//query for <sub name="Y"> and use the first found item
$subY = $xpath->query('//sub[@name="Y"]')->item(0);

//create <design> element
$design = $xml->createElement('design');
//add attributes
$design->setAttribute('name', 'J');
$design->setAttribute('path', 'folder');
//append it to the found <sub> element
$subY->appendChild($design);


//optional format output 
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;

//output XML
echo $xml->saveXML();

会导致:

<?xml version="1.0"?>
<user>
  <prop name="A">
    <sub name="X"/>
  </prop>
  <prop name="B">
    <sub name="Y">
      <design name="J" path="folder"/>
    </sub>
  </prop>
</user>