Quote:Original post by Zahlman
If the XML schema is under your control, consider that the fact that you want to be able to do this suggests a design problem.
Instead:
*** Source Snippet Removed ***
Alternatively if its under your control you can not have to deal with xml at all and use the xml serializer, I know it looks complex but the advantage is you can serialize a entire tree of objects all at once automatically.
using System;using System.Collections.Generic;using System.Xml;using System.Xml.Serialization;using System.IO;namespace XmlTest{ public class Blah { public Blah() {} public Blah(int type) { Type = type; } [XmlAttribute("type")] public int Type { get; set; } } [XmlRoot("root")] public class XmlExample { private List<Blah> list = new List<Blah>(); [XmlElement("blah")] public Blah[] ListItems { get { return list.ToArray(); } set { list = new List<Blah>(); list.AddRange(value); } } public void Add(Blah blah) { list.Add(blah); } } class XmlManager { public void Save(string path,XmlExample obj) { XmlSerializer s = new XmlSerializer(obj.GetType()); TextWriter w = new StreamWriter(path); s.Serialize(w, obj); w.Close(); } public XmlExample Load(string path) { XmlExample obj = new XmlExample(); XmlSerializer s = new XmlSerializer(obj.GetType()); TextReader r = new StreamReader(path); obj = (XmlExample)s.Deserialize(r); r.Close(); return obj; } }}
use
XmlExample test = new XmlExample();test.Add(new Blah(1));test.Add(new Blah(2));test.Add(new Blah(3));XmlManager xman = new XmlManager();xman.Save("..\\..\\xml\\test.xml", test);
for output
<?xml version="1.0" encoding="utf-8"?><root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <blah type="1" /> <blah type="2" /> <blah type="3" /></root>