/// <summary> /// Creates a new instance of XMLTree /// </summary> /// <param name="version">XML version</param> /// <param name="encoding">File encoding</param> public XMLTree(string version, Encoding encoding) { this.version = version; this.encoding = encoding; main = new XMLTag("xml"); main.Params.Add(new XMLParam("version", version)); main.Params.Add(new XMLParam("encoding", encoding.WebName)); main.Enclosing_Level = -1; }
/// <summary> /// Loads XMLTree object from a file /// </summary> /// <param name="file_path">File path</param> /// <returns>A XMLTree</returns> public static XMLTree LoadFrom(string file_path) { XMLTag tag = new XMLTag("xml"); string version = ""; Encoding enc = Encoding.Default; StreamReader sr = new StreamReader(file_path); string line = ""; do { line = sr.ReadLine(); } while (!line.Contains("<?xml")); tag.Params.AddRange(XMLTag.LoadParamsFromXMLTag(line)); for (int i = 0; i < tag.Params.Count; i++) { if (tag.Params[i].Name == "version") { version = tag.Params[i].Value; } if (tag.Params[i].Name == "encoding") { enc = Encoding.GetEncoding(tag.Params[i].Value); } } XMLTree tree = new XMLTree(version, enc); XMLTag last = tree.MainTag; /*new XMLTag("xml");*/ sr.Close(); sr = new StreamReader(file_path, enc); do { line = sr.ReadLine(); } while (!line.Contains("<?xml")); while (!sr.EndOfStream) { line = sr.ReadLine(); if (line.Contains("<") && !IsTagClosing(line)) { string name = ""; string val = ""; if (line.Contains(" ") && line.IndexOf(' ') < line.IndexOf('>')) { name = line.Substring(line.IndexOf('<') + 1, line.IndexOf(' ') - (line.IndexOf('<') + 1)); //antes -1 } else { name = line.Substring(line.IndexOf('<') + 1, line.IndexOf('>') - line.IndexOf('<') - 1); } val = XMLTag.LoadValueFromXMLTag(line); //XMLTag child = tree.MainTag.AddChild(name, val, LoadParamsFromXMLTag(line)); int i = 0; if (line.StartsWith("\t")) { while (line[i] == '\t') { i++; } } if (last.Enclosing_Level < i) { last = last.AddChild(name, val, XMLTag.LoadParamsFromXMLTag(line)); } else { if (i == 0) { last = tree.MainTag.AddChild(name, (i == 0 ? true : false)); last.Body = val; last.Params.AddRange(XMLTag.LoadParamsFromXMLTag(line)); } else { XMLTag tagIterator = tree.MainTag; for (int j = 0; j < tagIterator.Children.Count; j++) { if (tagIterator.Enclosing_Level == i - 1) { last = tagIterator.AddChild(name, val, XMLTag.LoadParamsFromXMLTag(line)); break; } else { tagIterator = tagIterator.Children[tagIterator.Children.Count - 1 - j]; j--; } } } } } } sr.Close(); return(tree); }
/// <summary> /// Adds a new XMLTag child /// </summary> /// <param name="child">XMLTag child</param> public void AddChild(XMLTag child) { child.Enclosing_Level = enclosing_level + 1; children.Add(child); }