0

例如有一个标签

<book>
<firstHalf>  </firstHalf>

<secondHalf>   </second half>
</book>

我的要求是我需要将上半年和下半年分开,如下所示

<book>
<firstHalf>  </firstHalf>
</book>
<book>
<secondHalf> </second half>
</book>

所以首先我需要添加一个新的结束书标签,然后是一个开始书标签!p- 使用 linq

我不知道该怎么做,任何帮助将不胜感激。

4

1 回答 1

0
var xmlStr = @"<root>
    <book>
        <firstHalf></firstHalf>
        <secondHalf></secondHalf>
    </book>
</root>
";
var doc = XDocument.Parse(xmlStr);

// find all books
var books = doc.Descendants("book").ToList();
    // p.s., need ToList() since we're modifying the structure
foreach (var book in books)
{
    // get all the "extra" elements
    var extraElements = book.Elements().Skip(1).ToList();
    if (extraElements.Any())
    {
        // remove the extra elements from the current book
        extraElements.Remove();
        // create new books after this book with the extra element
        book.AddAfterSelf(extraElements.Select(e => new XElement("book", e)));
    }
}

产量:

<root>
  <book>
    <firstHalf></firstHalf>
  </book>
  <book>
    <secondHalf></secondHalf>
  </book>
</root>
于 2012-09-02T03:07:46.457 回答