C# xml 序列化的问题。 现在有对象 IEnumerable xmlData,实现将其序列化到xml文件中指定节点nodeName

seshaliang 2011-08-31 10:47:22
现在有对象 IEnumerable<T> xmlData,实现将其序列化到xml文件中指定节点nodeName.
注意问题
1.XML文件中现在已经有数据,格式与即将写入的相同。
2.因为我对这块代码不熟,需要具体的实现代码。

public void SeriToXml<T>(string xmlFileName, XName nodeName, IEnumerable<T> xmlData) where T:class
{}
...全文
137 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

public void SeriToXml<T>(string xmlFileName, XName nodeName, IEnumerable<T> xmlData) where T : class
{
var xml = new System.Xml.XmlDocument();
System.Xml.XmlNode node = null;
try
{
xml.Load(xmlFileName);
node = xml.SelectSingleNode(nodeName); //如果有多个相同节点自己处理一下
}
catch
{
throw;
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8))
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(IEnumerable<T>));
xs.Serialize(xtw, xmlData);
if (node != null)
node.InnerXml = xtw.ToString();
//或者node.AppendChild(xml.CreateNode(System.Xml.XmlNodeType.Element, "nodeName", typeof(T).Namespace));
xtw.Close();
}
}
}
  • 打赏
  • 举报
回复
上面忘了调用xml.Save(xmlFileName)方法保存文件了
用linq只是强类型查询,你这里是要保存文件,所以用文件流可能对IO更合适
try
{
xdoc = XDocument.Load(xmlFileName, LoadOptions.PreserveWhitespace);
element = xdoc.Element(nodeName); //查询
//element = xdoc.Descendants().FirstOrDefault(n => n.Name == nodeName);
}
seshaliang 2011-09-01
  • 打赏
  • 举报
回复
辛苦等答案~~
seshaliang 2011-08-31
  • 打赏
  • 举报
回复
卖火柴的小女孩 正在等待答案。。。。 愁人啊,写不出来。

111,119

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧