我有一个如下所示的 XML 文件:
我正在尝试添加新书,但很明显,我陷入了无限循环。如果不重新评估查询中的书籍,我该如何做到这一点。看来我正在附加文件然后重新评估导致问题。
我尝试使用 for 循环
进行迭代,但没有得到想要的结果。
<?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");
最佳答案
将您的代码更新为:
List<XElement> books =
(from el in root.Descendants("book")
where el.Element("author").Value == "Ralls, Kim"
select el).ToList();
如果我没看错,应该可以解决问题。
重要的部分是 ToList()
,它使 linq 查询仅计算一次并将该初始结果用于所有后续用例。
关于c# - 如何在不导致无限循环的情况下向 XML 文件添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738640/