Sort XML with date

  • Thread starter Thread starter fix
  • Start date Start date
F

fix

Hi all,

I have an XML document look like this:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<piece dateorigin="2004/1/18 4:38" dateentry="2004/1/18 4:38">
</piece>
<piece dateorigin="2004/1/19 4:38" dateentry="2004/1/19 4:38">
</piece>
</root>

I follow the example in the help
ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfsystemxmlxpathxpathexpressioncla
ssaddsorttopic.htm
it generally works except sorting the date, the AddSort method accepts only
numbers or strings as sort keys. Is there anyone have any ideas?

I am using VS.NET 2002 with .NET framework 1.1.
Thanks.
fix.
 
I think You can use 2 ways:
1. Using XSL-template for transformation your xml to target xml by using
<xsl:sort > tag:
<xsl:sort select=root/piece /@dateorigin order='ascending'/>

2. AddSort method has this declaration:
public abstract void AddSort(object, IComparer);
Create your own class implemented IComparer and add there compare rules.
 
OK thanks. I didn't see that the AddSort is overloaded. I am not using XSLT
and so I go to your second suggestion, which works great.

--
 
Hm...... I got another problem.
I have written a DateComparer class implements IComparer, and I checked it
works fine.
But when I run these few lines with strFile as the file name, my
DateComparer class keeps getting two empty strings in the input of its
Compare method. Is there anything wrong?

Dim xmlFile As New XPathDocument(strFile)
Dim navFile As XPathNavigator = xmlFile.CreateNavigator()
Dim xpathSelection As XPathExpression
xpathSelection = navFile.Compile("//journal/piece")
xpathSelection.AddSort("dateorigin", New DateComparer())

DateComparer class:
Public Class DateComparer
Implements IComparer

Function Compare(ByVal x As Object, ByVal y As Object) As Integer
Implements IComparer.Compare
Dim Date1 As Date = CDate(x)
Dim Date2 As Date = CDate(y)

Return Date1.CompareTo(Date2)
End Function
End Class

--
 
Back
Top