XPathNavigator iterate and write
-
I am using XPathNavigator to sort nodes by name. Is there a method for writing the sorted nodes to the same or different file?
foreach( XPathNavigator item in navigator.Select( expr ) ) { // write to new document here..., }
Thanks, Mark
How about something like this?
static void Main(string\[\] args) { XDocument x = XDocument.Parse(sXml); Reorder(x.FirstNode); x.Save(newFileName); } private static void Reorder(XNode node) { var kids = (from nd in node.XPathSelectElements("\*") orderby nd.Name.LocalName select nd).ToList(); if (kids.Count>1) { (node as XElement).ReplaceNodes(kids); } kids.ForEach(f => Reorder(f)); }
-
How about something like this?
static void Main(string\[\] args) { XDocument x = XDocument.Parse(sXml); Reorder(x.FirstNode); x.Save(newFileName); } private static void Reorder(XNode node) { var kids = (from nd in node.XPathSelectElements("\*") orderby nd.Name.LocalName select nd).ToList(); if (kids.Count>1) { (node as XElement).ReplaceNodes(kids); } kids.ForEach(f => Reorder(f)); }
The xml is displayed in a TreeView control so alphabetical sorting by 'name' attribute was necessary. I worked out something similar to your reply and problem solved. Haven't had a prior occasion to use Linq however. Thanks for the help!
modified on Friday, December 3, 2010 3:28 PM
-
The xml is displayed in a TreeView control so alphabetical sorting by 'name' attribute was necessary. I worked out something similar to your reply and problem solved. Haven't had a prior occasion to use Linq however. Thanks for the help!
modified on Friday, December 3, 2010 3:28 PM
of course not. ( there are several ways as you'd expect, heres one, not the best not the worst ) how's this ?
static void Main(string\[\] args) { string newFileName = "c:\\\\myfilename.xml"; XmlDocument docSource = new XmlDocument(); docSource.LoadXml(XML); Reorder(docSource.DocumentElement); docSource.Save(newFileName); } private static void Reorder(XmlNode node) { SortedList childlist = SortedChildNodes(node); node.RemoveAll(); for (int i = 0; i < childlist.Count; i++) { Reorder(node.AppendChild(childlist.Values\[i\])); } } static SortedList SortedChildNodes(XmlNode node) { SortedList ret = new SortedList(); for (int i = 0; i < node.ChildNodes.Count; i++) { string name = node.ChildNodes\[i\].Name; XmlNode nd = node.ChildNodes\[i\]; ret.Add(name, nd); } return ret; }