我有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>有人能帮我吗?谢谢
发布于 2019-06-28 03:24:49
由于您没有服务的WSDL文件,所以您可以使用Visual的鲜为人知的特性( 粘贴XML作为类 )使用.NET 4.5中引入的类生成特性。
使用此功能的步骤如下:
然后,Visual将使用为XML请求生成的类填充类文件。
注意:示例XML当前格式错误,信封元素上的xmlns:tem属性没有关闭。如果XML格式错误,则此特性将无法工作。
发布于 2019-06-27 22:20:03
你不需要上课。在本例中,我认为解析字符串并在列表中添加项目更容易。见下面的代码:
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);
}
}
}https://stackoverflow.com/questions/56798694
复制相似问题