2014-10-16 38 views
0

单个XML记录集中可以有一个或多个类似的XML标签。如果有很多,我需要他们在一个标签,逗号分隔。 这是我现在拥有的XML。如何连接XML文件中的类似标签

<?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> 

我需要它是这样的。请帮助一个代码。

<?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> 
+2

在要求为您编写代码之前,请尝试自己解决问题。 – Maccath 2014-10-16 09:55:38

回答

0

这可以用xpath完成。这里是的SimpleXML一个例子:

你可以先找到所有的第一个叶子:

foreach ($xml->xpath('//*[not(*) and not(preceding-sibling::*)]') as $firstLeaf) { 
    ... 
} 

,然后你用下面所有的叶子一起Concat的文本:

$followingWithSameName = 'following-sibling::*[name(.) = name(preceding-sibling::*[last()])]'; 
    // change the text of the first leaf 
    $firstLeaf[0] = implode(', ', $firstLeaf->xpath(".|$followingWithSameName")); 

和那么你删除所有以下叶子:

// remove all following leafs with the same name 
    foreach ($firstLeaf->xpath($followingWithSameName) as $leaf) { 
     unset($leaf[0]); 
    } 

Demo

+0

请参阅“[链接](http://stackoverflow.com/questions/26542442/how-to-concatenate-similar-tags-in-a-xml)”@hakre – Beginner 2014-10-24 06:17:02