Reverse XmlNodeList Order

  • Thread starter Thread starter eggie5
  • Start date Start date
E

eggie5

Hi,

I have an XmlNodeList and I need to reverse it. Just like
Array.Reverse(), but it has to stay as an XmlNodeList.

Any ideas?
 
You could try something like

List<XmlNode> children = new List<XmlNode>();
foreach (XmlNode child in myNode.ChildNodes)
{
children.Add(myNode.Remove(child));
}
for (int i = children.Count - 1; i >= 0; i--)
{
myNode.AppendChild(children);
}

It may not be the fastest, but it is a way. I have not tested it, but it
should be pretty close to the real thing :-)

HTH
 
OK... this is downright dirty, but it seems to work...

It does at least mean that it stays in sync with the source document (if
that respects updates... not sure)...

Marc

public class ReverseXmlList : XmlNodeList {
private readonly XmlNodeList _source;
public ReverseXmlList(XmlNodeList source)
{
_source = source;
}
public override XmlNode Item(int index)
{
return _source.Item(Count - (index + 1));
}
public override System.Collections.IEnumerator GetEnumerator()
{
for (int i = Count - 1; i >= 0; i--)
{
yield return _source.Item(i);
}
}
public override int Count
{
get { return _source.Count; }
}
}
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<Xml><A/><B/><C/></Xml>");
XmlNodeList original = doc.DocumentElement.ChildNodes;
XmlNodeList reverse = new ReverseXmlList(original);
foreach (XmlNode node in reverse)
{
Debug.WriteLine(node.Name);
}
Debug.WriteLine(reverse[0].Name);
Debug.WriteLine(reverse.Item(0).Name);
}
 
Hi,

What is myNode in your example? I need a reversed XmlNodeList to be
returned.

You could try something like

List<XmlNode> children = new List<XmlNode>();
foreach (XmlNode child in myNode.ChildNodes)
{
children.Add(myNode.Remove(child));}for (int i = children.Count - 1; i >= 0; i--)
{
myNode.AppendChild(children);

}It may not be the fastest, but it is a way. I have not tested it, but it
should be pretty close to the real thing :-)

HTH

I have an XmlNodeList and I need to reverse it. Just like
Array.Reverse(), but it has to stay as an XmlNodeList.
Any ideas?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top