【发布时间】:2012-03-24 12:13:01
【问题描述】:
尝试创建动态 XML 文件并将数据保存到其中,但是我能够保存最后一个条目而不是所有条目。有什么想法吗?
生成带有所需节点的 XML 文件:
GenerateXML()
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode albums = doc.CreateElement("albums");
doc.AppendChild(albums);
XmlNode album = doc.CreateElement("album");
albums.AppendChild(album);
XmlNode title = doc.CreateElement("title");
albums.AppendChild(title);
doc.Save(System.Windows.Forms.Application.StartupPath + "\\albums.xml");
按钮单击的输出给了我 10 条记录或 100 条记录或一些记录:
//album is a class returned by web service
if (Elements.Count > 0)
{
string path = System.Windows.Forms.Application.StartupPath + "\\albums.xml";
//Read the file stream in read mode
FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.Xml.XmlDocument albumSpecs = new System.Xml.XmlDocument();
albumSpecs.Load(READER);
FileStream WRITER = null;
GenerateXML();
//Create a FileStream for writing
WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//albums");
for (int i = 0; i < ResultsList.Items.Count - 1; i++)
{
album = (Album)ResultsList.Items[i];
foreach (XmlNode node in nodes)
{
node["title"].InnerText = album.Title;
}
}
//Write the data to the filestream
doc.Save(WRITER);
}
我得到了 XML 中的最后一个条目数据,而不是所有返回的条目。
<?xml version="1.0" encoding="UTF-8"?>
<albums>
<album />
<title>She will be loved</title>
</albums>
如何根据返回的条目数构建运行时 XML?
【问题讨论】:
-
您只能在 doc 中创建一组元素,就像您的代码现在的工作方式一样。您不会与结果集合同步迭代元素集合。您永远不会丢弃您的 READER 或 WRITER。您用新的输出覆盖您的文档,而无需对您加载到 albumSpecs 中的旧信息做任何事情。我建议你仔细看看你的代码并修改这个问题。这是作业吗?
-
-1 没有足够的信息来弄清楚你想要什么
标签: c# .net xml winforms c#-2.0