如何选择不同的 xml 节点

发布于 2024-08-27 09:59:28 字数 664 浏览 5 评论 0原文

如何在 C# 中的 XML 中获取不同的节点列表,

例如

<root>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
</root>

在此 XML 中,我将获取不同的节点 并使这个 xml

<root>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
</root>

这个 xml 不是真实的示例,我在全局模式下为 xml 中的任何结构寻找解决方案

How to take distinct nodes list in XML in c#

for example

<root>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
</root>

in this XML i will take distinct node
and make this xml

<root>
<node1 ss="d1" ff="f1" gg="h1"/>
<node1 ss="d1" ff="f2" gg="h1"/>
<node1 ss="d2" ff="f1" gg="h1"/>
</root>

this xml is sample not real and i look for a solution in global mode for any struct in xml

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

近箐 2024-09-03 09:59:28

您可以通过多种方式做到这一点;例如,xslt 中的 Muenchian 分组。但在 C# 中,如果 xml 布局已知且固定,也许最简单的方法是:

        var root = XElement.Parse(xml);
        var newRoot = new XElement("root",
            root.Elements("node1").Select(el =>
            new {
                ss = (string)el.Attribute("ss"),
                ff = (string)el.Attribute("ff"),
                gg = (string)el.Attribute("gg"),
            }).Distinct().Select(obj =>
                new XElement("node1",
                    new XAttribute("ss", obj.ss),
                    new XAttribute("ff", obj.ff),
                    new XAttribute("gg", obj.gg))));

如果您需要更灵活的东西,则使用 IEqualityComparer (与 .Distinct()< 一起使用) /code>) 会更有价值。

Various ways you could do that; Muenchian grouping in xslt for example. But in C#, if the xml layout is known and fixed, perhaps the easiest would be:

        var root = XElement.Parse(xml);
        var newRoot = new XElement("root",
            root.Elements("node1").Select(el =>
            new {
                ss = (string)el.Attribute("ss"),
                ff = (string)el.Attribute("ff"),
                gg = (string)el.Attribute("gg"),
            }).Distinct().Select(obj =>
                new XElement("node1",
                    new XAttribute("ss", obj.ss),
                    new XAttribute("ff", obj.ff),
                    new XAttribute("gg", obj.gg))));

If you need something more flexible, an IEqualityComparer<XElement> (for use with .Distinct()) would be more valuable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文