分解XML文件中的属性


Explode the attribute in XML File

我有一个XML,其属性如下:

<products>
<product ProductName="One" ProductCategory="Software::Utilities::Email">
<product ProductName="Two" ProductCategory="Software::Video::Editing">
<product ProductName="Three" ProductCategory="Software::Audio::Converter">
</products>

我如何分解"ProductCategory"属性并像这样将其分离:

<products>
<product ProductName="One" ProductCategory="Software">
<product ProductName="One" ProductCategory="Utilities">
<product ProductName="One" ProductCategory="Email">
<product ProductName="Two" ProductCategory="Software">
<product ProductName="Two" ProductCategory="Video">
<product ProductName="Two" ProductCategory="Editing">
<product ProductName="Three" ProductCategory="Software">
<product ProductName="Three" ProductCategory="Audio">
<product ProductName="Three" ProductCategory="Converter">
</products>

示例

<?php
$string = <<<XML
<products>
    <product ProductName="One" ProductCategory="Software::Utilities::Email"></product>
    <product ProductName="Two" ProductCategory="Software::Video::Editing"></product>
    <product ProductName="Three" ProductCategory="Software::Audio::Converter"></product>
</products>
XML;
$xml = simplexml_load_string($string);
$obj = json_decode(json_encode($xml), true);
$new_xml = '<products>';
foreach($obj['product'] as $val){
    $name = $val['@attributes']['ProductName'];
    $pro = explode('::', $val['@attributes']['ProductCategory']);
    foreach($pro as $k=>$v){
        $new_xml .= '<product ProductName="'.$name.'" ProductCategory="'.$v.'"></product>';
    }
}
$new_xml .= '</products>';
$file = fopen("test.xml","w");
fwrite($file, $new_xml);
fclose($file);
?>

示例XML不是有效的XML。请确保关闭产品元素节点。

将源文档加载到DOM中,创建一个新的目标DOM。将文档元素导入到目标中(不包含子元素)。这将创建该节点的副本。

迭代产品节点并读取ProductCategory属性,将其分解为一个数组。迭代数组并将节点复制到目标文档中(对于每个值),将属性更改为值。

$source = new DOMDocument();
$source->loadXml($xml);
$xpath = new DOMXPath($source);
$target = new DOMDocument();
$target->formatOutput = true;
$root = $target->appendChild($target->importNode($source->documentElement));
foreach ($xpath->evaluate('/products/product') as $node) {
  $list = explode('::', $node->getAttribute('ProductCategory'));
  foreach ($list as $value) {
    $newNode = $root->appendChild($target->importNode($node));
    $newNode->setAttribute('ProductCategory', $value);
  }
}
echo $target->saveXml();

演示:https://eval.in/209729