使用 ArrayOfString 基于 XML 请求生成 C# 类

Posted

技术标签:

【中文标题】使用 ArrayOfString 基于 XML 请求生成 C# 类【英文标题】:Generating C# classes based on XML request using ArrayOfString 【发布时间】:2019-11-09 22:15:47 【问题描述】:

我有 xml 请求,我需要为列表结构生成 c# 类。

请求:

  <soapenv:Envelope  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org"
      xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays ">
     <soapenv:Header/>
      <soapenv:Body>
      <tem:request>
         <tem:id>1</tem:id>
         <tem:list>
            <arr:string>Item1</arr:string>
            <arr:string>Item2</arr:string>
            <arr:string>Item3</arr:string>
         </tem:list>
      </tem:request>
   </soapenv:Body>
  </soapenv:Envelope>

有人可以帮我吗? 谢谢

【问题讨论】:

您是否有要集成的服务的 WSDL(服务定义)文件? 不,只是请求。 请求是一个字符串而不是类。序列化产生一个字符串。您可以使用 doc.ToString() 从我的解决方案中获取字符串。 【参考方案1】:

由于您没有服务的 WSDL 文件,您可以使用 Visual Studio 的鲜为人知的功能 Paste XML as Class,它使用 .NET 4.5 中引入的类生成功能。

使用此功能的步骤是:

    创建要插入 XML 的 Class 文件。 将光标放在类文件中,单击编辑 -> 选择性粘贴 -> 将 XML 粘贴为类。

然后,Visual Studio 将使用为您的 XML 请求生成的类填充类文件。

注意:您的示例 XML 当前格式不正确,xmlns:tem 属性未在信封元素上关闭。如果 XML 格式错误,此功能将不起作用。

【讨论】:

【参考方案2】:

您不需要课程。我认为在这种情况下,解析字符串并在列表中添加项目会更容易。请参阅下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1

    class Program
    
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        
            List<string> items = new List<string>() "Item1", "Item2", "Item3";
            string xml = 
                "<soapenv:Envelope  xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org\"" +
                      " xmlns:arr=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">" +
                     "<soapenv:Header/>" +
                      "<soapenv:Body>" +
                      "<tem:request>" +
                         "<tem:id>1</tem:id>" +
                         "<tem:list>" +
                         "</tem:list>" +
                      "</tem:request>" +
                   "</soapenv:Body>" +
                  "</soapenv:Envelope>";

            XDocument doc = XDocument.Parse(xml);
            XElement root = doc.Root;
            XNamespace temNs = root.GetNamespaceOfPrefix("tem");
            XNamespace arrNs = root.GetNamespaceOfPrefix("arr");

            XElement list = doc.Descendants(temNs + "list").FirstOrDefault();

            List<XElement> xItems = items.Select(x => new XElement(arrNs + "string", x)).ToList();

            list.Add(xItems);
            doc.Save(FILENAME);
        
    

【讨论】:

以上是关于使用 ArrayOfString 基于 XML 请求生成 C# 类的主要内容,如果未能解决你的问题,请参考以下文章

基于ssm框架没有pom.xml正常吗

基于xml架构在VSCode中自动完成xml标记

如何在 Access2007 中使用基于 Visual Studio (2008/2010) 构建的 XML Web 服务

带有 JSON 数组的 Jquery - 转换为 Javascript 数组

Spring IOC的初始化过程——基于XML配置

使用 XML 创建自定义进度条