XML数据排序

 

根据XML数据的Index 来进行排序

 

方法一:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XMLOrderby
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Configuration>
  <ModulePermit>
    <Mast Code=""S001"" Name=""系统维护"" Index=""1"">
      <Sub Code=""S00101"" Name=""地区管理"" Index=""1""></Sub>
      <Sub Code=""S00102"" Name=""管理员管理"" Index=""2""></Sub>
    </Mast>
    <Mast Code=""S002"" Name=""业务管理"" Index=""2"">
      <Sub Code=""S00201"" Name=""收货管理"" Index=""2""></Sub>
      <Sub Code=""S00202"" Name=""发货管理"" Index=""2""></Sub>
      <Sub Code=""S00203"" Name=""报表管理"" Index=""3""></Sub>
    </Mast>
  </ModulePermit>
</Configuration>";

            XDocument doc = XDocument.Parse(xml);
            var Query = from D in doc.Element("Configuration").Element("ModulePermit").DescendantNodes()
                        orderby XElement.Parse(D.ToString()).Attribute("Index").Value
                        select new
                        {
                            Code = XElement.Parse(D.ToString()).Attribute("Code").Value,
                            Name = XElement.Parse(D.ToString()).Attribute("Code").Value,
                            Index = XElement.Parse(D.ToString()).Attribute("Index").Value
                        };
            foreach (var v in Query)
            {
                Console.WriteLine("Code={0}     Name={1}       Inex={2}", v.Code, v.Name, v.Index);
            }
            Console.ReadKey();
        }
    }
}

 

 

方法二:

 

XDocument doc = XDocument.Parse(xml);
            var Query = from D in doc.Element("Configuration").Element("ModulePermit").DescendantNodes()
                        let Index = XElement.Parse(D.ToString()).Attribute("Index").Value
                        let Code = XElement.Parse(D.ToString()).Attribute("Code").Value
                        orderby Index, Code
                        select new
                        {
                            Code = Code,
                            Name = XElement.Parse(D.ToString()).Attribute("Name").Value,
                            Index = Index
                        };

 

 

你可能感兴趣的:(xml,LINQ)