我这样打电话:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
var line = reader.ReadLine();
}
“行”内容是:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="...." xmlns:xsd="..." xmlns:xsi=".....">
<soap:Body>
<findResponse xmlns="....">
<out>
<MyType>
<city>CityA</city>
<firstName>AAA</firstName>
<lastName>A</lastName>
</MyType>
<MyType>
<city>CityB</city>
<firstName>BBB</firstName>
<lastName>B</lastName>
</MyType>
</out>
</findResponse>
</soap:Body>
</soap:Envelope>
public class MyType
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
我想返回一个List,在这种情况下有两个条目。
我该怎么做?
谢谢,
答案 0 :(得分:1)
这样的事情怎么样:
var list = XDocument.Load(response.GetResponseStream())
.Descendants("MyType")
.Select(elem => new MyType
{
FirstName = elem.Element("firstName").Value,
LastName = elem.Element("lastName").Value,
City = elem.Element("city").Value
}).ToList();
另外,HttpWebResponse
实现IDisposable
并且应该放在using
内。因此整个命令可能如下所示:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var list = XDocument.Load(response.GetResponseStream())
.Descendants("MyType")
.Select(elem => new MyType
{
FirstName = elem.Element("firstName").Value,
LastName = elem.Element("lastName").Value,
City = elem.Element("city").Value
}).ToList();
}
更新:这可能是命名空间问题:
XNamespace ns = "http://www.your-namespace.com";
var list = XDocument.Load(response.GetResponseStream())
.Descendants(ns + "MyType")
.Select(elem => new MyType
{
FirstName = elem.Element("firstName").Value,
LastName = elem.Element("lastName").Value,
City = elem.Element("city").Value
}).ToList();
答案 1 :(得分:0)
从你的“line”创建一个xml,其中out标记为root,然后将其转换为json,然后将json反序列化为List:
var myListOfMyType = JsonConvert.DeserializeObject(myJson, typeof(MyType));