Musings
Public · Protected · Private
Walking (drill)thru an XML with XmlReader
-
2012-05-18 04:34Given //////////////sample XML <a> <aa></aa> <ab> </ab> <ac> <aca></aca> <acb></acb> <acc> www <acca></acca></acc> <accont q="q" >some content</accont> </ac> </a> we want to validate XML for two custom conditions. 1. This XML cannot have Attributes. 2. Each node can contain either "childnodes" or content. Not both
-
2012-05-18 04:45Solution Start with 3 classes //Composite pattern as Datastructure. public class anything { protected List<anything> children = null; public bool HasContent; } public class Leafnode : anything { public string mytext { get; set; } } public class Nonleafnode : anything { public Nonleafnode() { children = new List<anything>(); } public void AddChild(Nonleafnode ch) { children.Add(ch); } } // recursor and pointers private string filename = "c:\\myxml.xml"; XmlTextReader reader = null; private bool ReadANode(XmlTextReader rr, Nonleafnode currentNode) { while (rr.Read()) { string a = rr.Name; string b =rr.Value; if (rr.NodeType == XmlNodeType.Text) { currentNode.HasContent = true; } else if (rr.NodeType == XmlNodeType.EndElement) { return true; } else if (rr.NodeType == XmlNodeType.Element) { if ((!currentNode.HasContent) &&(!string.IsNullOrEmpty(rr.Value))) currentNode.HasContent = true; else if (currentNode.HasContent) return false; else if (rr.HasAttributes) return false; else { bool mychildGood = true; Nonleafnode child = new Nonleafnode(); currentNode.AddChild(child); mychildGood = ReadANode(rr, child); if (!mychildGood) return mychildGood; } } } return true; } // Caller private void button1_Click(object sender, EventArgs e) { reader = new XmlTextReader(filename); reader.WhitespaceHandling = WhitespaceHandling.None; bool isCorrect = true; Nonleafnode rootnode = new Nonleafnode(); isCorrect = ReadANode(reader, rootnode); if (!isCorrect) { MessageBox.Show("Failed" + " Failed @ node " + reader.Name + reader.Value); } reader.Close(); }
This blog is frozen. No new comments or edits allowed.