2016-03-04 78 views
0

我有這些項要素:如何根據Xdocument中的同胞值將新元素內的同胞元素分開?

<Entry> 
    <pos STYLE="NUM">1</pos > 
    <tran></tran> 
    <pos STYLE="NUM">2</pos > 
    <example></example> 
    <pos STYLE="NUM">3</pos > 
    <elem></elem> 
</Entry> 
<Entry> 
    ... 
</Entry> 

我怎樣才能變換元素num元素添加到新的元素之間,到底我有這樣的:

<Entry> 
    <body> 
    <tran></tran> 
    </body> 
    <body> 
    <example></example> 
    </body> 
    <body> 
    <elem></elem> 
    </body> 
</Entry> 

編輯::我SOFAR加載XML文檔遍歷所有元素,並做了一些格式是無關緊要這個問題

XDocument doc = XDocument.Load(sourceDocument,LoadOptions.PreserveWhitespace); 
foreach (XElement rootElement in doc.Root.Elements()) 
{ 
    foreach (XElement childElement in rootElement.Descendants()) 
    { 
     //add new body if <pos style=num> 
     if (childElement.Attribute("STYLE") != null) 
     { 
      //if next node is NUM 
      var nextNode = childElement.XPathSelectElement("following-sibling::*"); 

      if (nextNode != null) 
      if (nextNode.Attribute("STYLE").Value == "NUM") 
      { 
       newBodyElem = new XElement("body"); 
      } 
} 
} 
+0

代碼在哪裏? –

+0

@HeinA.Grønnestad你需要更詳細的代碼嗎?我認爲這是相關部分 –

+0

泰姆Eronen沒有代碼,當我評論... –

回答

0

它可以被看作是一個分組問題,其restructu res條目內容:

 XDocument doc = XDocument.Load("input.xml"); 
     foreach (XElement entry in doc.Descendants("Entry").ToList()) 
     { 
      foreach (var group in entry.Elements().Except(entry.Elements("pos")).GroupBy(child => child.ElementsBeforeSelf("pos").Last())) 
      { 
       group.Remove(); 
       group.Key.ReplaceWith(new XElement("body", group)); 
      } 
     } 
     doc.Save("output.xml"); 
相關問題