How to transform XML for one XSD into another XML format that is very similar but has a different XSD file?

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

How to transform XML for one XSD into another XML format that is very similar but has a different XSD file? The XSD is quite large and has many complex types, but the actual XML looks very similar.

I have two XSD files and two XML files - they both validate successfuly to one of the XSD files. I would like to transform one of the XML files into the other so that I can use only one class for further operations.

How do I do this in .NET 4.0 and c# 4.0 ? Do I have to use XSLT or something? If I do have to use XSLT, how do I do this? I'm not sure I'm looking forward to creating an XSLT document.

It was kind of a nightmare using AutoMapper to convert one XML class into the other. When I looked at the XML it was so similar so I thought there may be an easier way...

回答1:

I would definitely use XSLT. If the XML is very similar, it shouldn't be too difficult. Start with an identity transform and then override it when something needs to change.

The following example only changes "foo" elements to "bar" elements.:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:output indent="yes"/>   <xsl:strip-space elements="*"/>    <!--Identity Template. This will copy everything as-is.-->   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>    <!--Change "foo" element to "bar" element.-->   <xsl:template match="foo">     <bar>       <xsl:apply-templates select="@*|node()"/>     </bar>   </xsl:template>  </xsl:stylesheet>

Resources:

http://www.w3.org/TR/xslt

http://www.jenitennison.com/xslt/

http://www.mulberrytech.com/quickref/XSLT_1quickref-v2.pdf

http://www.mulberrytech.com/xsl/xsl-list/index.html#archive

Also, a huge part of XSLT is XPath. If you don't have a development tool (my favorite is oXygen, @DimitreNovatchev has a great tool called the XPath Visualizer.



回答2:

I used Altova MapForce to generate a XSLT file. The interface is easy to use by loading the source and destination XSD/DTD files and then mapping the matching elements. Then use .NET to transform the source XML to destination XML using the XSLT file.

http://www.altova.com/mapforce.html

http://msdn.microsoft.com/en-us/library/14689742.aspx



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!