Most of the examples I’ve found on sorting an XML query do not include a namespace. Some of them do, but I’m not finding any example of performing a query and sorting when there is a namespace.
<Search xmlns="http://whatever.whatever.com/gg/whatever">
<BinSet Type="Category">
<Bin>
<BinName>Clothing</BinName>
<BinItemCount>804</BinItemCount>
<BinParameter>
<Name>Category</Name>
<Value>Women's Apparel</Value>
</BinParameter>
</Bin>
<Bin>
<BinName>Tools</BinName>
<BinItemCount>126</BinItemCount>
<BinParameter>
<Name>Category</Name>
<Value>Tools, handtools and hardware</Value>
</BinParameter>
</Bin>
</BinSet>
</Search>
I don’t have any control of the XML, so I have to deal with the namespace. Also, There are approximately 50 of these records in the XML and it is only part of a much larger XML file.
Dim nsuri as string = "http://whatever.whatever.com/gg/whatever"
Dim xpath as string = "dd:Search/dd:BinSet[Type="Category"]/*"
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim exp As XPathExpression = nav.Compile(xpath)
Dim nsmgr As New XmlNamespaceManager(nav.NameTable)
nsmgr.AddNamespace("dd", nsuri)
exp.SetContext(nsmgr)
exp.AddSort("BinParameter/Value", XmlSortOrder.Ascending, XmlCaseOrder.UpperFirst, "en-US", XmlDataType.Text)
' now process in sorted order
Dim iterator As XPathNodeIterator = nav.Select(exp)
While iterator.MoveNext
Dim nav2 As XPathNavigator = iterator.Current.Clone
nav2.MoveToFirstChild()
Debug.WriteLine(nav2.Value)
End While
All of the examples I’ve seen show how to sort on the immediate child nodes, for example BinName or BinItemCount in my example XML. But I need all of this information and I need to sort on the BinParameter/Value node. I’ve tried every way I can think of…
One last thing to note, I don’t really care to use an XPathNodeIterator or XPathNavigator when all is said and done. Previously I was returning an XmlNodeList with all these records and my calling routine would traverse the nodelist to form links, like this:
<a href="mypage.aspx?si=Tools">Tools, handtools and hardware (126)</a>
<a href="mypage.aspx?si=Clothing">Women's Apparel (804)</a>
Does anyone know how to sort this XML by the nested child node “Value” using a namespace?
Also, would you know the quickest way to return the sorted results in an XmlNodeList or other .Net object so that I can have access to all of the values: BinName, BinItemCount, Name and Value? I’m not familiar with XPathNavigator or XPathNodeIterator.
Thank you.
Try setting the
xpathvariable toand use the following AddSort line
(note the
dd:prefix to all elements)EDIT: