views:

230

answers:

3

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?

A: 

If you can control the .xsd maybe this post offers a starting point.

When changing the schema isn't an option you could still transform your xml to the desired structure.

Filburt
Ya, I read a way to do it with "xs:choice" and it can allow multiple selections, but I don't necessarily have xsd control (this is for a large company app). Eventually I just resorted to doing a sort, using the order in the .xsd with a custom comparitor to sort the elements, then re-added them back to the main XML document.
Kevin
@Kevin Good to hear you got it to work. I myself would have rather used xslt on the output so i'd not get bitten by unexpected changes in the merge result somewhere in the future.
Filburt
+1  A: 

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,

Marvin Smit
+1  A: 

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.

John Saunders