0

Is there a way we can sort xmlnodes based on attribute values? The point is that every child node has a different name, despite it, I want to sort them by attribute.
E.g.

<Doc>
<mar_03 data="03">
  <Mattina_Turno_1 />
</mar_03>
<dom_01 data="01">
  <Mattina_Turno_1 />
</dom_01>
<mer_04 data="04">
  <Mattina_Turno_1 />
  <Mattina_Turno_2 />
</mer_04>
</Doc>

Should become

<Doc>
<dom_01 data="01">
  <Mattina_Turno_1 />
</dom_01>
<mar_03 data="03">
  <Mattina_Turno_1 />
</mar_03>
<mer_04 data="04">
  <Mattina_Turno_1 />
  <Mattina_Turno_2 />
</mer_04> </Doc>

How can I do it? After sorting obviously I want to overwrite the file.

This answer does not fix my problem since i can not define the node "item" since every my nodes are named differently.

Thanks, and please do not mark it as duplicate, because it is not!

2

2 Answers 2

1

Please try,

XDocument xdoc = XDocument.Load("File.xml");

        var result = xdoc.Element("Doc")
        .Elements()
        .OrderBy(s => (int)s.Attribute("data"));

        string xmlOutPut = string.Empty;

        result.ToList().ForEach(a =>
        {
            xmlOutPut += a;
        });

Where data and Doc is the parent element is your attribute according to your example. File.xml is your xml file name. You will get the sorted output in 'xmlOutPut'

or everything in a single Linq query,

XDocument xdoc = XDocument.Load("XMLFile2.xml");
        string xmlOutPut = string.Empty;

        xdoc.Element("Doc")
          .Elements()
          .OrderBy(s => (int)s.Attribute("data"))
         .ToList().ForEach(a =>
         {
             xmlOutPut += a;
         });
Sign up to request clarification or add additional context in comments.

1 Comment

what about the two "element"? Should not they be the nodes name?
0

Sorting

XDocument xDoc = XDocument.Load("FileName.xml");

    var res = xDoc.Element("Doc")
                    .Elements()
                    .OrderByDescending(c => (int) c.Attribute("data"));

Then to save it:

XDocument doc = new XDocument(new XElement("Doc", res));
doc.Save("FileName.xml");

3 Comments

OP has one file in which the nodes should be sorted.
Should not we define that the attribute "data" are in the doc child nodes?
I edit the answer , but you should define the attribute data to sort the element determined on value inside attribute data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.