Reordering XML nodes according to defined schema
I'm merging a coupl开发者_C百科e 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?
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,
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.
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.
精彩评论