简体   繁体   English

如何从xpath创建XML文档

[英]How to create an XML document from xpath

I need to transform my domain object into an xml document for a third party data exchange. 我需要将我的域对象转换为xml文档以进行第三方数据交换。

I have a mapping document with the location of the data from my domain and an xpath of where this data exports into the xml document. 我有一个映射文档,其中包含来自我的域的数据的位置以及此数据导出到xml文档的xpath。

What I am looking to do is build an engine that will read this mapping file pull the data out of my domain object and build the proper xml document. 我要做的是构建一个引擎,它将读取此映射文件从我的域对象中提取数据并构建正确的xml文档。

My current difficulty is while taking the xpaths to build I need to ensure that the xml sequences are placed in the correct order. 我目前的困难是在构建xpath时我需要确保xml序列以正确的顺序放置。

Any suggestions on how to approach this? 有关如何处理此问题的任何建议?

** I am trying to avoid bringing in classes representing xml documents in to my code base. **我试图避免将代表xml文档的类引入我的代码库。 This way we can add a new export with out recompiling the project. 这样我们就可以添加新的导出而无需重新编译项目。

I'm going to suggest something a little different than what you're asking, because I've found xpath a bit cumbersome and when I first started using LINQ to XML it was a mini revolution of happiness within me. 我会建议一些与你所要求的有点不同的东西,因为我发现xpath有点麻烦,当我第一次开始使用LINQ to XML时,这是我内心的一次小小的幸福革命。

One of the advantages here is that if you ever decide you want to serialize differently, there's little code change, you simply need to find a Linq to (Json, SQL, etc) library (of which there are many, and things like SQL are provided by Microsoft) and make very minor code changes. 这里的一个优点是,如果您决定要进行不同的序列化,那么代码更改很少,您只需要找到一个Linq到(Json,SQL等)库(其中有很多,像SQL这样的东西)由Microsoft提供)并进行非常小的代码更改。

Check out Linq to Xml on msdn. 在msdn上查看Linq to Xml

If you think that you might be interested in this, or more about Linq, I found the book Linq in Action to be a very good book to get the basics down. 如果您认为您可能对此感兴趣,或者更多关于Linq,我发现Linq in Action这本书是一本非常好的书,可以帮助您掌握基础知识。

It would be easiest for you generate type libraries from the contracts exposed on the various interfaces you need to generate messages for. 最简单的方法是从生成消息所需的各种接口上公开的合同生成类型库。 You can do this with xsd.exe or svcutil.exe for wcf endpoints. 对于wcf端点,可以使用xsd.exe或svcutil.exe执行此操作。

Then if you need to generate a xml instance for a specific interface you simply popluate an instance of the type for the interface and use XmlSerializer.Serialize() to serialize an instance message for that interface. 然后,如果需要为特定接口生成xml实例,只需弹出该接口类型的实例,并使用XmlSerializer.Serialize()为该接口序列化实例消息。

This has the benefits: 这有以下好处:

  1. that your xml instances will conform to the endpoint schemas 您的xml实例将符合端点模式
  2. you do not need to hand-crank the xml out each time 你不需要每次都用手摇动xml

If you want me to explain any of the steps in more detail let me know via a comment. 如果您希望我更详细地解释任何步骤,请通过评论告诉我。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM