Linq to XML,强制在已存在的标记之间关闭和打开标记

时间:2012-09-02 02:51:43

标签: xml linq

有一个标签,例如

<book>
<firstHalf>  </firstHalf>

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

我的要求是我需要分开下半部分,如下所示

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

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

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

1 个答案:

答案 0 :(得分: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>