Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering XML nodes according to defined schema

Tags:

c#

.net

xml

xsd

I'm merging a couple of .xml files together, and need to take certain child elements from each .xml document and put them into a 3rd. And that's OK, but the problem is that then my "child" nodes are in a somewhat random order (well, what I picked from the first file, followed by what I picked from the 2nd), and the schema file (the .xsd) defines these children as a "sequence" or xs:sequence if you prefer. So the output file then doesn't pass validation anymore because while each file had its elements in order, the resulting file does not.

What I'm wondering, is that since I have the .xsd, and I have a "mostly" valid .xml file, is there any way in C# to "move" all the nodes into the correct order according to the order defined in the .xsd without a lot of pain? Obviously I could implement a kind of "sort" but I'm hoping there's something built-in. Or better yet, a built-in merge that does this automatically could also work.

Any ideas?

like image 424
Kevin Anderson Avatar asked Oct 28 '25 21:10

Kevin Anderson


2 Answers

Looking at the requirements, is it an option to have an XSD model guide you?

You would load the XSD into an XmlSchema class. Now you can get the model. By walking over the children of the schema nodes you will have guarenteed ordering. So, bassically

  • collect the nodes from the 3 sub documents and put them in a working doc (not the target doc yet).
  • Run through the schema defined structure to build the target document
  • Select the nodes from the working doc based on the order of the schema nodes (by element name/namespace-uri) and place them in the final target document

Hope this helps,

like image 75
Marvin Smit Avatar answered Oct 31 '25 11:10

Marvin Smit


Take a look at the XmlSchemaValidator Class. Tihs class performs a "push-based" validation - it effectively tells you what's valid next. Perhaps you can use this to reorder your XML. I have been able to use it to generate sample XML that conforms to a schema.

like image 43
John Saunders Avatar answered Oct 31 '25 11:10

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!