C#: Sort xml node using attribute value

后端 未结 1 1612
萌比男神i
萌比男神i 2020-12-18 17:20

Is there a way we can sort xmlnodes based on attribute values, consider I can\'t use linq. Since I\'m using .NET 2.0.

Example:



        
1条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 18:04

    To sort use following:

    var xml= xDoc.Element("Root")
                    .Elements("I")
                    .OrderByDescending(s => (int) s.Attribute("aa"));
    

    Then to save it:

    XDocument doc = new XDocument(new XElement("Root", xml));
    doc.Save("C:\\Something.xml");
    

    UPDATE

    You can use XSLT for this:

    
        
            
                
                                
                        
                
            
        
    
    

    And invoke it (quoting How to apply an XSLT Stylesheet in C# ):

    XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
    XslTransform myXslTrans = new XslTransform() ;
    myXslTrans.Load(myStyleSheet);
    XmlTextWriter myWriter = new XmlTextWriter("result.xml",null) ;
    myXslTrans.Transform(myXPathDoc,null,myWriter) ;
    

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