我有一个XML文档,我想按字母顺序对特定节点进行排序。
XML文档
<response>
<lst name="facet_counts">
<lst name="facet_fields">
<lst name="professions_raw_nl">
<int name="Pharmacy">2724</int>
<int name="Physiotherapy">2474</int>
<int name="Doctor">2246</int>
<int name="Dentist">1309</int>
</lst>
</lst>
</lst>
</response>
期望的输出
牙医(1309)
医生(2246)
药房(2724)
物理治疗(2474)
当前的ASP.NET代码
dim node as XmlNode = objXML.SelectSingleNode("response/lst[@name=""facet_counts""]/lst[@name=""facet_fields""]/lst[@name=""professions_raw_nl""]")
Dim sbuilder As New StringBuilder
Dim navigator As XPathNavigator = node.CreateNavigator()
Dim selectExpression As XPathExpression = navigator.Compile("???") <-- what expression should I use here ???
selectExpression.AddSort("????", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text) <-- what expression should I use here ????
Dim nodeIterator As XPathNodeIterator = navigator.Select(selectExpression)
While nodeIterator.MoveNext()
'how can I print the name and value of the node?
End While
答案 0 :(得分:0)
如果您使用.Net&gt; = 3.5,那么您可以使用linq为您执行此操作
var xmlString = "YOUR XML STRING";
var doc = XDocument.Parse(xmlString);
var list = doc. Descendants("int").select(n=>new {Name = n.Attribute("name").Value, Value = n.Value});
var sortedList = list.OrderBy(l=>l.Name);
编辑不是VB中的专家,但试试这个 - 请在这里可能存在语法错误
dim xmlString as string
xmlString = "YOUR XML STRING"
dim doc as XDocument()
doc = XDocument.Parse(xmlString)
dim list = doc.Descendants("int").select(n=>new {Name = n.Attribute("name").Value, Value = n.Value}).OrderBy(l=>l.Name)
LINQ代表语言集成查询..并且比你当前使用的东西更容易和统一..你可以阅读更多here
答案 1 :(得分:0)
我尝试了以下代码并且它正在运行(C#)您可以获得如下的值
var doc = new XmlDocument();
doc.Load("c:\\users\\ozgur\\sample.xml");
var nav = doc.CreateNavigator();
var node = nav.SelectSingleNode("response").SelectSingleNode("lst[@name=\"facet_counts\"]").SelectSingleNode("lst[@name=\"facet_fields\"]").SelectSingleNode("lst[@name=\"professions_raw_nl\"]").Select("int");
var sorted = new SortedDictionary<string, string>();
while (node.MoveNext())
{
var name = node.Current.SelectSingleNode("@name").Value;
var value = node.Current.Value;
sorted.Add(name, value);
}
foreach (var item in sorted)
{
item.Key.ToString();
item.Value.ToString();
}
答案 2 :(得分:0)
由于所有答案似乎都与Linq一起工作,我只是想使用常规VB.NET,现在我在Arraylist中添加了每个节点,并在其上使用了常规的Array.Sort()。 诀窍。