本文介绍了如何串联XML文件中的相似标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
单个XML记录集中可以有一个或多个类似的XML标签.如果有很多,我需要将它们放在一个标签中,以逗号分隔.这是我现在拥有的XML.
There can be one or many similar XML tags inside a single XML record set. If there are many, I need them to be in a one tag, comma separated.This is the XML I have now.
<?xml version="1.0"?>
<Results>
<Recordset setCount="3">
<Record setEntry="0">
<AU>One</AU>
<AU>Two</AU>
<AU>three</AU>
</Record>
<Record setEntry="1">
<AU>One</AU>
<AU>Two</AU>
<AU>Three</AU>
<AU>Four</AU>
<AU>Five</AU>
<AU>Six</AU>
<AU>Seven</AU>
</Record>
<Record setEntry="2">
<AU>One</AU>
</Record>
</Recordset>
</Results>
我需要像这样.请提供代码帮助.
I need it to be like this. Please help with a code.
<?xml version="1.0"?>
<Results>
<Recordset setCount="3">
<Record setEntry="0">
<AU>One, Two, Three</AU>
</Record>
<Record setEntry="1">
<AU>One, Two, Three, Four, Five, Six, Seven</AU>
</Record>
<Record setEntry="2">
<AU>One</AU>
</Record>
</Recordset>
</Results>
推荐答案
这可以通过xpath完成.这是 Simplexml 的示例:
This can be done with xpath. Here is an example with Simplexml:
您可以首先找到所有第一个叶子:
You can first find all the first leafs:
foreach ($xml->xpath('//*[not(*) and not(preceding-sibling::*)]') as $firstLeaf) {
...
}
然后将文本与以下所有叶子合并在一起:
and then you concat the text together with all the following leafs:
$followingWithSameName = 'following-sibling::*[name(.) = name(preceding-sibling::*[last()])]';
// change the text of the first leaf
$firstLeaf[0] = implode(', ', $firstLeaf->xpath(".|$followingWithSameName"));
,然后删除以下所有叶子:
and then you remove all the following leafs:
// remove all following leafs with the same name
foreach ($firstLeaf->xpath($followingWithSameName) as $leaf) {
unset($leaf[0]);
}
这篇关于如何串联XML文件中的相似标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!