使用 C# 按字母数字对 XML 节点进行排序
假设我生成的 XmlDocument
具有如下所示的 InnerXml
:
<ORM_O01>
<MSH>
<MSH.9>
<MSG.2>O01</MSG.2>
</MSH.9>
<MSH.6>
<HD.1>13702</HD.1>
</MSH.6>
</MSH>
<ORM_O01.PATIENT>
<PID>
<PID.18>
<CX.1>SecondTestFin</CX.1>
</PID.18>
<PID.3>
<CX.1>108</CX.1>
</PID.3>
</PID>
</ORM_O01.PATIENT>
</ORM_O01>
如您所见,节点
位于之前节点
。 (
也在
之前。)
重组我的生成会导致我漂亮的干净代码变得非常混乱。
有没有办法对节点进行排序,以便对 alpha 进行排序,直到到达最后一个句点,然后对数字进行排序(如果最后一个值是数字)?
通过“数字排序”,我的意思是它会查看整个数字而不是逐个字符。 (所以18>3)。
Say I have an XmlDocument
that I generate that has InnerXml
that looks like this:
<ORM_O01>
<MSH>
<MSH.9>
<MSG.2>O01</MSG.2>
</MSH.9>
<MSH.6>
<HD.1>13702</HD.1>
</MSH.6>
</MSH>
<ORM_O01.PATIENT>
<PID>
<PID.18>
<CX.1>SecondTestFin</CX.1>
</PID.18>
<PID.3>
<CX.1>108</CX.1>
</PID.3>
</PID>
</ORM_O01.PATIENT>
</ORM_O01>
As you can see node <PID.18>
is before node <PID.3>
. (<MSH.9>
is also before <MSH.6>
.)
Restructuring my generation would cause my nice clean code to become very messy.
Is there a way to sort the nodes so that it will sort alpha until it hits the last period then sort numeric (if the last values are numbers)?
By "numeric sorting" I mean it will look at the whole number rather than char by char. (So 18 > 3).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
显而易见的答案是肯定的。
如果这是你想要的结果:
那么这个类会做到这一点:(我应该为此得到报酬...)
有人可能能够写出这个更干净、更刻薄的代码,但这应该让你继续下去。
The obvious answer is yes.
If this is the result you want:
Then this class will do it: (I should get paid for this...)
Someone may be able to write this cleaner and meaner, but this should get you going.
对你的问题感兴趣,所以这是我的两分钱。
我已经实现了
IComparer
来处理元素比较和两个处理递归的方法。代码可以清理一下,但我已经粘贴了我创建的控制台应用程序代码,以向您展示我的解决方案,我认为该解决方案效果很好。编辑: 为了使本文更易于阅读,我将其分解为核心部分,尽管我已经离开了功能控制台应用程序
IComparer实现:
处理递归的方法:
功能控制台应用程序:
Was interested in your question so here is my two cents.
I've implemented
IComparer<T>
to handle the element comparisons and two methods which handle recursion. The code could be cleaned up a bit but I've pasted in the console application code I created to show you my solution which I think worked out well.Edit: To make this easier to read I've broken this down into the core parts though I've left the functional console app
IComparer<T>
Implementation:Methods for handling the recursion:
Functional Console Application:
利用
System.Xml.Linq
,此代码可能会对您有所帮助。用法:
SortXml
函数:utilizing
System.Xml.Linq
, this code may help you.Usage:
SortXml
function:另一种尝试,使用修改后的 Dotnet.Commons.Xml。
在此处获取 XmlUtils 类。
创建一个包含所有逻辑的自定义比较器(这将帮助您继续)
然后修改 XmlUtils SortElements 函数,将其添加到顶部:
CustomComparer comparer = new CustomComparer();
并将该行更改
为:
Yet another attempt, using a modified Dotnet.Commons.Xml.
Get the XmlUtils class here.
Create a custom Comparer that has all your logic (this will get you going)
Then modify the XmlUtils SortElements function, add this to the top:
CustomComparer comparer = new CustomComparer();
and change the line:
to
这个来自 Java2S.com 的解决方案有什么用吗?
Would this solution from Java2S.com be of any use?