我在排序XML查詢時發現的大多數示例都不包含名稱空間。他們中的一些人,但我沒有找到任何執行查詢和排序時有一個名稱空間的例子。使用命名空間對XML進行排序
<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>
我沒有任何對XML的控制,所以我不得不處理命名空間。此外,XML中有大約50個這樣的記錄,它只是更大的XML文件的一部分。
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
所有我見過的表演如何排序直接子節點上的例子,例如BINNAME或BinItemCount在我的示例XML。但是我需要所有這些信息,我需要在BinParameter/Value節點上排序。我嘗試了所有我能想到的方法...
最後要注意的是,當所有事情都說完之後,我並不在乎使用XPathNodeIterator或XPathNavigator。以前我是用所有的這些記錄返回一個XmlNodeList中,我的調用程序會遍歷節點列表,形成鏈接,就像這樣:
<a href="mypage.aspx?si=Tools">Tools, handtools and hardware (126)</a>
<a href="mypage.aspx?si=Clothing">Women's Apparel (804)</a>
有誰知道如何通過嵌套子節點「值」使用這個XML排序命名空間?另外,你會知道在XmlNodeList或其他.Net對象中返回排序結果的最快方法,這樣我就可以訪問所有的值:BinName,BinItemCount,Name和Value嗎?我不熟悉XPathNavigator或XPathNodeIterator。
謝謝。
對不起...我沒有包含我的XPath聲明。它包含前綴。它是: – rwkiii 2012-04-25 21:23:16
是的? (請注意,您的AddSort表達式不包含名稱空間前綴) – erikxiv 2012-04-25 21:29:08
難以理解如何回覆......抱歉。我會嘗試你的建議。我唯一擔心的是我還需要BinName和BinItemCount的值。所以我的XPath已經是/ dd:Sets/dd:Bin。通過將XPath設置得像你推薦的那樣深,看起來這些值不會被包括在內?我會嘗試並讓你知道。謝謝!順便說一下,我的XPath確實包含了適當的名稱空間前綴。 – rwkiii 2012-04-25 21:59:30