如何在ASP.NET中从XML文件提取指定的客户及配送地址数据
只提取并展示指定XML字段的解决方案
嘿,看你已经搞定了XML数据提取和基础展示功能,现在想精简成只保留Customer的Id、Name、Address,还有ShippingAddress的对应字段对吧?我来给你一步步调整代码,完美实现需求~
1. 精简并完善ViewModel
首先咱们把ViewModel改得更贴合需求,只保留需要展示的字段,同时新增ShippingAddressViewModel来对应XML里的收货地址结构:
// CustomerViewModel.cs public class CustomerViewModel { public string Id { get; set; } public string Name { get; set; } public string Address { get; set; } // 新增收货地址集合,用来存放多个ShippingAddress public List<ShippingAddressViewModel> ShippingAddresses { get; set; } = new List<ShippingAddressViewModel>(); } // 新建ShippingAddressViewModel.cs public class ShippingAddressViewModel { public string Id { get; set; } public string Name { get; set; } public string Address { get; set; } }
2. 修改数据提取逻辑,只保留目标字段
你原来的代码会把Customer下的所有字段都映射进去,而且没处理ShippingAddresses部分。现在咱们调整提取逻辑,只过滤出需要的字段,同时补上收货地址的提取:
XmlNodeList customerNodes = xmlDocument.SelectNodes("//Customer"); // 注意去掉原代码里//后面的空格,否则会找不到节点 List<CustomerViewModel> customerList = new List<CustomerViewModel>(); foreach (XmlNode node in customerNodes) { CustomerViewModel customer = new CustomerViewModel(); // 定义Customer需要保留的字段清单 var requiredCustomerFields = new List<string> { "Id", "Name", "Address" }; XmlNodeList fieldNodes = node.SelectNodes("field"); foreach (XmlNode fieldNode in fieldNodes) { string attrName = fieldNode.Attributes["name"].Value; string attrValue = fieldNode.Attributes["value"].Value; // 只处理咱们需要的字段 if (requiredCustomerFields.Contains(attrName) && customer.GetType().GetProperty(attrName) != null) { customer.GetType().GetProperty(attrName).SetValue(customer, attrValue); } } // 处理XML里的ShippingAddresses节点 XmlNode shippingAddressesNode = node.SelectSingleNode("ShippingAddresses"); if (shippingAddressesNode != null) { XmlNodeList shippingAddressNodes = shippingAddressesNode.SelectNodes("ShippingAddress"); var requiredShippingFields = new List<string> { "Id", "Name", "Address" }; foreach (XmlNode addrNode in shippingAddressNodes) { ShippingAddressViewModel shippingAddr = new ShippingAddressViewModel(); XmlNodeList addrFieldNodes = addrNode.SelectNodes("field"); foreach (XmlNode fieldNode in addrFieldNodes) { string attrName = fieldNode.Attributes["name"].Value; string attrValue = fieldNode.Attributes["value"].Value; // 同样只保留收货地址的指定字段 if (requiredShippingFields.Contains(attrName) && shippingAddr.GetType().GetProperty(attrName) != null) { shippingAddr.GetType().GetProperty(attrName).SetValue(shippingAddr, attrValue); } } customer.ShippingAddresses.Add(shippingAddr); } } customerList.Add(customer); }
3. 前端展示只渲染需要的字段
现在customerList里已经只有你需要的数据了,不管是用Razor视图展示还是返回API数据,直接渲染指定字段就行。比如Razor视图的示例:
@foreach (var customer in Model.CustomerList) { <div class="customer-card"> <h3>@customer.Name (ID: @customer.Id)</h3> <p>客户地址: @customer.Address</p> <h4>收货地址:</h4> <ul> @foreach (var addr in customer.ShippingAddresses) { <li> @addr.Name (地址ID: @addr.Id)<br> 地址详情: @addr.Address </li> } </ul> </div> }
这样就完全实现了只提取和展示你指定的字段,代码也更简洁高效~
内容的提问来源于stack exchange,提问作者Shaun
相关产品推荐
相关产品推荐

