我有以下XML数据。
<userAddress>
<addr>
<streetAddress/>
<streetAddress>some street</streetAddress>
<streetAddress>town</streetAddress>
<streetAddress>city</streetAddress>
<streetAddress>London</streetAddress>
<postCode>L45 1SG</postCode>
</addr>
</userAddress>
我正在尝试阅读每个街道地址行,并使用以下代码将值存储在变量中。
XElement elem = XElement.Parse(xmldata);
var address = elem.Descendants("addr").ToList();
foreach (var adr in address)
{
current_user.address_1 = addr.Element("streetAddress").Value.ToString();
current_user.address_2 = addr.Element("streetAddress").Value.ToString();
current_patient.address_3 = addr.Element("streetAddress").Value.ToString();
current_patient.address_4 = addr.Element("streetAddress").Value.ToString();
current_patient.address_5 = addr.Element("streetAddress").Value.ToString();
current_patient.post_code = addr.Element("postCode").Value;
}
我面对上述代码的问题是它将streetAddress的第一行值分配给所有变量address_1,address_2,address_3,address_4,address_5。
答案 0 :(得分:0)
如果您想要地址列表,那么您可以直接获取元素。然后,您必须根据您的标准分配值
XElement elem = XElement.Parse(xmldata);
IEnumerable<XElement> addresses = elem.Descendants("streetAddress");
现在你可以遍历这个并分配值。