Sort XML nodes alphabetically on attribute name

前端 未结 3 1435
栀梦
栀梦 2021-01-07 13:17

I have an XML document for which I want to sort specific nodes alphabetically.

XML document


    

        
相关标签:
3条回答
  • 2021-01-07 13:45

    if you are using .Net>=3.5 then you can use linq to do this for you like this

    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);
    

    EDIT not a pro in VB but try this - pls there may be syntactical errors in here

    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 stands for Language Integrated Query.. and is a lot easier and Uniform that the thing you are using currently.. you can read more here

    0 讨论(0)
  • 2021-01-07 14:02

    I tried the following code and it is working (C#) you can get values as below

            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();
            }
    
    0 讨论(0)
  • 2021-01-07 14:03

    Since all answers seem to work with Linq and I just wanted to use regular VB.NET I now added each node in an Arraylist and used the regular Array.Sort() on it. Does the trick.

    0 讨论(0)
提交回复
热议问题