简体   繁体   English

使用Linq对XML进行复杂排序

[英]Complex sorting of XML using Linq

I've tried to find a solution for my problem, but my knowledge in this area (Linq, XML) is rather limited. 我试图为我的问题找到解决方案,但我在这方面的知识(Linq,XML)相当有限。 :( 've found a simular construction , but I need a litte bit more complex way of sorting. :('我发现了一个类似的结构 ,但我需要一个更复杂的排序方式。

Consider the Following XML document: 考虑以下XML文档:

<Envelope>
    <Body>
        <Table>
            <Trans>
                <B>1</B>
                <A>3</A>
                <C>5</C>
            </Trans>
            <Trans>
                <D>1</D>
                <A>6</A>
                <C>3</C>
            </Trans>
            <Trans>
                <A>1</A>
                <C>3</C>
                <B>5</B>
            </Trans>
        </Table>
    </Body>
<Envelope>

Is there any way I can sort the elements inside <Trans> using C#/Linq, or do I have to break up all <Trans> elements and sort them one by one? 有什么方法可以使用C#/ Linq对<Trans>中的元素进行排序,还是我必须拆分所有<Trans>元素并逐个排序?

Update I have a file and this is what I'm tring to accomplish. 更新我有一个文件,这是我要完成的。 ;) ;)

<Envelope>
    <Body>
       <Table>
           <Trans>
               <A>3</A>
               <B>1</B>
               <C>5</C>
           </Trans>
           <Trans>
               <A>6</A>
               <C>3</C>
               <D>1</D>
           </Trans>
           <Trans>
               <A>1</A>
               <B>5</B>
               <C>3</C>
           </Trans>
       </Table>
   </Body>
<Envelope>

It really depends on what exactly you want to do (process them in order, or reorder the XML?) and on what exactly you mean "sort" (sort by tag name? sort by value?). 这实际上取决于你想要做什么(按顺序处理它们,或重新排序XML?)以及你究竟是什么意思“排序”(按标签名称排序?按值排序?)。

If you just want to process them in order, this is how you can sort all elements inside each <Trans> by value ( <D>1</D> before <A>6</A> ): 如果您只是想按顺序处理它们,这就是如何按值( <A>6</A> <D>1</D><A>6</A>之前)对每个<Trans>内的所有元素进行排序:

XDocument doc = /* load up your XML */

var sorted = from trans in doc.Descendants("Trans")
             select trans.Children().OrderBy(c => int.Parse(c.Value)).ToArray();

Alternatively, here's how to order by tag name ( <A>6</A> before <D>1</D> ): 或者,这里是如何按标签名称( <A>6</A> <D>1</D>之前的<A>6</A>订购:

var sorted = from trans in doc.Descendants("Trans")
             select trans.Children().OrderBy(c => c.Name.LocalName).ToArray();

With the above, sorted will be an enumerable collection of arrays. 有了上面的内容, sorted将是一个可枚举的数组集合。 Each array in the collection represents a <Trans> , and each such array holds the children of the <Trans> in order. 集合中的每个数组代表一个<Trans> ,每个这样的数组按顺序保存<Trans>的子<Trans>

XDocument xDoc = XDocument.Load(....);
foreach(var trans in xDoc.Descendants("Trans"))
{
    trans.ReplaceAll( trans.Elements().OrderBy(x=>x.Name.LocalName));
}

string newXml = xDoc.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM