XML拆分节点。值 [英] XML Split Node on . value

查看:186
本文介绍了XML拆分节点。值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了SO多年,总是找到一个答案,但这一次我已经很好,真的迷失了。

I've used SO for many years and always found an answer but this time I have got myself well and truly lost.

我有一个xml文件喜欢将兼容性分解成良好的xml

I have an xml file I would like to split the compatbility into well formed xml

`<product>
<item>
<partno>abc123</partno>
<Compatbility>model1: 110C, 115C, 117C. model2: 1835C, 1840C. model3: 210C, 215C, 3240C.</Compatbility>
</item>
</product>`

在兼容性中,单词模型随着每个项目条目而改变,后:模特总是在那里。每个模型组之后。

In Compatbility the word model changes with each item entry although the : after model is always there as is the . after each model group.

我应该使用SimpleXml DomXml或xpath来获得以下结果

Should I use SimpleXml DomXml or an xpath to get the following result

`<product>
<item>
<partno>abc123</partno>
<Compatbility>
<model>model1: 110C, 115C, 117C.</model>
<model>model2: 1835C, 1840C.</model> 
<model>model3: 210C, 215C, 3240C.</model>
</Compatbility>
</item>
</product>`

谢谢

推荐答案

首先,您需要先将其转换为可以操作的数组(数组)。然后通常解析(使用爆炸)。最后,您将需要再次创建一个新的xml。考虑这个例子:

First ofcourse, you need to convert that first into something that you can manipulate (arrays). Then the usual parsing (using explode). In the end, you will need to create a new xml again. Consider this example:

$xml_string = '<product><item><partno>abc123</partno><Compatbility>model1: 110C, 115C, 117C. model2: 1835C, 1840C. model3: 210C, 215C, 3240C.</Compatbility></item></product>';
$original_xml = simplexml_load_string($xml_string);
$data = json_decode(json_encode($original_xml), true);
$compatbility = $data['item']['Compatbility']; // get all compatibility values
// explode values
$compatbility = array_filter(array_map('trim', explode('.', $compatbility)));

$new_xml = new SimpleXMLElement('<product/>'); // initialize new xml
// add necessary values
$new_xml->addChild('item')->addChild('partno', $data['item']['partno']);
$new_xml->item->addChild('Compatbility');
// loop the values and add them as children
foreach($compatbility as $value) {
    $value = trim(preg_replace('/(\w+):/', '', $value));
    $new_xml->item->Compatbility->addChild('model', $value);
}
echo $new_xml->asXML(); // output as xml

这篇关于XML拆分节点。值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆