Description : In the listview you have items in the form of Happy=Coding Hello=wORLD
You want to export the listview items to xml.XML should look like:
< ?xml version="1.0" encoding="utf-8"? > < Collection > < Details Name="Happy" Val="Coding" / > < Details Name="Hello" Val="World" / > < /Collection >
Now during exporting it has to check if the file already exist or not.If it doesnot exist it should create a new xml file.And in case the file already exist then it should add the listview items before the rootnode.
private bool ExportToXML() { FileStream fleStream; StreamWriter stmWriter; XmlTextWriter xmlTxtWriter; string filepath = Application.StartupPath + "/" + "myxml.xml"; try { if (File.Exists(filepath)) { fleStream = new FileStream("myxml.xml", FileMode.Append, FileAccess.Write, FileShare.None); stmWriter = new StreamWriter(fleStream); xmlTxtWriter = new XmlTextWriter(stmWriter); xmlTxtWriter.Formatting = Formatting.Indented;
XmlDocument originalXml = new XmlDocument(); stmWriter.Close(); originalXml.Load(filepath);
for (int i = 0; i < this.lstNameVal.Items.Count; i++) { string[] s = this.lstNameVal.Items[i].ToString().Split('='); XmlNode coll = originalXml.SelectSingleNode("//Collection"); XmlNode det = originalXml.CreateNode(XmlNodeType.Element, "Details", null); XmlAttribute xa = originalXml.CreateAttribute("Name"); xa.Value = s[0].ToString(); XmlAttribute xb = originalXml.CreateAttribute("Val"); xb.Value = s[1].ToString(); coll.AppendChild(det); det.Attributes.Append(xa); det.Attributes.Append(xb);
} originalXml.Save(filepath);
} else { fleStream = new FileStream("myxml.xml", FileMode.CreateNew, FileAccess.Write, FileShare.None); stmWriter = new StreamWriter(fleStream); xmlTxtWriter = new XmlTextWriter(stmWriter); xmlTxtWriter.Formatting = Formatting.Indented; xmlTxtWriter.WriteStartDocument(); xmlTxtWriter.WriteStartElement("Collection");
for (int i = 0; i < this.lstNameVal.Items.Count; i++) { string[] s = this.lstNameVal.Items[i].ToString().Split('='); xmlTxtWriter.WriteStartElement("Details"); xmlTxtWriter.WriteAttributeString("Name", s[0].ToString()); xmlTxtWriter.WriteAttributeString("Val", s[1].ToString()); xmlTxtWriter.WriteEndElement();
}
xmlTxtWriter.WriteEndDocument();
xmlTxtWriter.Flush(); xmlTxtWriter.Close(); } return true; } catch (IOException ex) { ex.ToString(); return false; } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|