我有一个如下所示的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:\source\catalog.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:\dest\catalog.xml");
答案 0 :(得分:1)
将代码更新为:
List<XElement> books =
(from el in root.Descendants("book")
where el.Element("author").Value == "Ralls, Kim"
select el).ToList();
如果我没看错,应该可以解决问题。
重要的部分是ToList()
,它使linq查询仅评估一次,并将该初始结果用于以后的所有用例。