如何将数据添加到XML文件中而不会引起无限循环



我有一个XML文件,如下所示:我正在尝试添加新书,但很明显,我被卡住了一个无限的循环。在不重新评估查询的书籍的情况下,我该怎么做。看来我正在附加文件,然后重新评估引起问题。我尝试使用迭代的for loop,但没有欲望结果。

<?xml version="1.0"?>
<catalog>
<item>
   <book>
      <author>Ralls, Kim</author>
      <title>XML Developer's Guide</title>
   </book>
</item>
<item>
   <book>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
   </book>
</item>
</catalog>

我需要在两个项目节点中添加一本书,以便每个项目总共基于作者。

结果看起来像这样:

<?xml version="1.0"?>
<catalog>
<item>
   <book>
      <author>Ralls, Kim</author>
      <title>XML Developer's Guide</title>
   </book>
   <book>
      <author>Ralls, Kim</author>
      <title>C# Developer's Guide</title>
   </book>
</item>
<item>
   <book>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
   </book>
   <book>
      <author>Ralls, Kim</author>
      <title>C# Developer's Guide</title>
   </book>
</item>
</catalog>

代码:

        XElement root = XElement.Load(@"C:sourcecatalog.xml");
        IEnumerable<XElement> books =
        from el in root.Descendants("book")
       where el.Element("author").Value == "Ralls, Kim"
        select el;
        foreach (XElement el in books)
        {
            el.AddAfterSelf
            (
            new XElement
            (
                "book", new XElement("author", "Ralls, Kim"),
                        new XElement("title", "C# Developer's Guide")
            )
            );
            Console.WriteLine(el.Value);
        }
        root.Save(@"C:destcatalog.xml");

将您的代码更新为:

List<XElement> books =
    (from el in root.Descendants("book")
    where el.Element("author").Value == "Ralls, Kim"
    select el).ToList();

如果我正确阅读本文,应该做一个问题。

重要的部分是ToList()它导致LINQ查询仅评估一次,并在所有以后的用例中使用该初始结果。

最新更新