我收到肥皂服务的回复。它看起来像:
<ArrayOfPaymentHistory_ST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<PaymentHistory_ST>
<tTRANSDATE>2015-01-05T08:58:17</tTRANSDATE>
<tPAIDTO>2015-02-01T00:00:00</tPAIDTO>
<dAMOUNT>110</dAMOUNT>
<dBALANCE>0</dBALANCE>
<TRANSKIND>Auto CC Payment</TRANSKIND>
<csUnit>Lee</csUnit>
</PaymentHistory_ST>
<PaymentHistory_ST>
<tTRANSDATE>2015-01-01T08:58:17</tTRANSDATE>
<tPAIDTO>2015-01-01T00:00:00</tPAIDTO>
<dAMOUNT>-110</dAMOUNT>
<dBALANCE>110</dBALANCE>
<TRANSKIND>Rent Posted</TRANSKIND>
<csUnit>Lee</csUnit>
</PaymentHistory_ST>
</ArrayOfPaymentHistory_ST>
我已经定义了这样的模型:
public class payment_history
{
public DateTime tTRANSDATE { get; set; }
public DateTime tPAIDTO { get; set; }
public double dAMOUNT { get; set; }
public double dBALANCE { get; set; }
public string TRANSKIND { get; set; }
}
我正在尝试解析此XML响应并创建payment_history类型的对象列表。 然后,我将在标记上发送此对象并显示在表格中。 我发现了许多使用XMLReader进行XML解析的帖子。我仍然无法找到一个可以优雅地做到这一点的好解决方案。
这是我的c#代码。
List<payment_history> ph = new List<payment_history>();
payment_history p = new payment_history();
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(soapResult)))
{
#region parseXML
while (reader.Read())
{
foreach (var el in reader.ReadOuterXml())
{
if (reader.IsStartElement())
{
//return only when you have START tag
switch (reader.Name.ToString())
{
case "tTRANSDATE":
p.tTRANSDATE = Convert.ToDateTime(reader.ReadString());
break;
case "tPAIDTO":
p.tPAIDTO = Convert.ToDateTime(reader.ReadString());
break;
case "dAMOUNT":
p.dAMOUNT = Convert.ToDouble(reader.ReadString());
break;
case "dBALANCE":
p.dBALANCE = Convert.ToDouble(reader.ReadString());
break;
case "TRANSKIND":
p.TRANSKIND = reader.ReadString();
break;
}
ph.Add(p);
}
}
}
#endregion
}
}
}
return ph;
有人可以指导这项工作吗?我是c#的新手。任何形式的帮助将不胜感激。
我尝试过遵循LINQ2XML。但是没有任何回报!!
ph = XDocument.Parse(soapResult)
.Descendants("PaymentHistory_ST")
.Select(g => new payment_history
{
tTRANSDATE = (DateTime)g.Element("tTRANSDATE"),
tPAIDTO = (DateTime)g.Element("tPAIDTO"),
dAMOUNT = (double)g.Element("dAMOUNT"),
dBALANCE = (double)g.Element("dBALANCE"),
TRANSKIND = (string)g.Element("TRANSKIND")
}).ToList();
答案 0 :(得分:2)
使用
XDocument doc = XDocument.Load(response.GetResponseStream());
XNamespace df = "http://tempuri.org/";
List<payment_history> ph = doc.Descendants(df + "PaymentHistory_ST")
.Select(g => new payment_history
{
tTRANSDATE = (DateTime)g.Element(df + "tTRANSDATE"),
tPAIDTO = (DateTime)g.Element(df + "tPAIDTO"),
dAMOUNT = (double)g.Element(df + "dAMOUNT"),
dBALANCE = (double)g.Element(df + "dBALANCE"),
TRANSKIND = (string)g.Element(df + "TRANSKIND")
}).ToList();