2014-10-16 60 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