【发布时间】:2017-04-19 19:55:31
【问题描述】:
我有一个集合字符串,其中包含姓名、性别等客户信息。所有客户都有一个 ID。
现在我想创建一个包含所有客户的通用 XML 文件。类似下面的例子:
<custumers>
<custumer>
<name></name>
<id></id>
<etc></etc>
</custumer>
</custumers>
没有xml文件启动很简单,我用linq创建xml文件。
对于初始创建,我使用了以下代码:
try
{
var xEle = new XElement("Customers",
from cus in cusList
select new XElement("Customer",
new XElement("Name", cus.Name),
new XElement("gender", cus.gender),
new XElement("etc", cus.etc));
}
xEle.Save(path);
但是,如果我想更新 XML 文件,我会遇到一些问题。 我的解决方法:
Iterate over all customers in list and check for all customers if the customer.id exists in the XML.
IF not: add new customer to xml
IF yes: update values
到目前为止我的代码:
var xEle = XDocument.Load(xmlfile);
foreach (cus in cusList)
try
{
var cids = from cid in xEle.Descendants("ID")
where Int32.Parse(xid.Element("ID").Value) == cus.ID
select new XElement("customer", cus.name),
new XElement ("gender"), cus.gender),
new XELement ("etc."), cus.etc)
);
xEle.Save(xmlpath);
}
【问题讨论】:
-
您想更新 XML?为什么不能直接重写?
-
如果我想重写它,我需要从现有的 XML 中加载所有数据。我不认为这是一个高效的解决方案。还是我错了?
-
检查每个 ID 会花费更多的 CPU 时间。不会吗?
-
听起来您想在 XML 文件的中间添加或修改一个节点。 XML 文件只是一个文本流而不是数据库;没有简单的方法可以在文本流中间插入。见Adding a Line to the Middle of a File with .NET。但要附加请参阅Fastest way to add new node to end of an xml? 或Appending an existing XML file with XmlWriter。最简单的解决方案是将 XML 加载到内存中,编辑节点,然后写入整个文件。
-
@dbc 谢谢,我会尝试一些不同的解决方案。