首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于XML请求使用C#生成ArrayOfString类

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

Stack Overflow用户
提问于 2019-06-27 21:30:40
回答 2查看 309关注 0票数 0

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

请求:

代码语言:javascript
复制
  <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>

有人能帮我吗?谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-28 03:24:49

由于您没有服务的WSDL文件,所以您可以使用Visual的鲜为人知的特性( 粘贴XML作为类 )使用.NET 4.5中引入的类生成特性。

使用此功能的步骤如下:

  1. 创建要插入的XML的类文件。
  2. 将光标放在类文件中,单击“编辑->粘贴特殊->粘贴为类”。

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

注意:示例XML当前格式错误,信封元素上的xmlns:tem属性没有关闭。如果XML格式错误,则此特性将无法工作。

票数 1
EN

Stack Overflow用户

发布于 2019-06-27 22:20:03

你不需要上课。在本例中,我认为解析字符串并在列表中添加项目更容易。见下面的代码:

代码语言:javascript
复制
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);
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56798694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档