我想用给定的参数反序列化我的 xml 文件。
AddressInfo deserialized;
XmlSerializer deserializer = new XmlSerializer(typeof(AddressInfo));
using (TextReader reader = new StreamReader(@"D:\dataAPIv2\dataAPI\Files\sample_data.xml"))
{
object obj = deserializer.Deserialize(reader);
deserialized = (AddressInfo)obj;
}
我可以在没有参数的情况下反序列化,这是有效的。但我想用 xpath 更改此操作以反序列化上述过程。
XmlDocument doc = new XmlDocument();
doc.Load(System.Web.HttpContext.Current.Server.MapPath("~/Files/sample_data.xml"));
XmlNodeList nodeList = doc.SelectNodes($"/AddressInfo/City[@code='{citycode}']"); // I want to accomplish this part."
foreach (XmlNode node in nodeList)
{
city.city_code = Convert.ToInt32(node.Attributes["code"].Value);
city.city_name = node.Attributes["name"].Value;
foreach (XmlNode subnode in node)
{
dist.district_name = subnode.Attributes["name"].Value;
dist.city_code = Convert.ToInt32(subnode.ParentNode.Attributes["code"].Value);
foreach (XmlNode xmlNode in subnode)
{
zip.district_name = xmlNode.ParentNode.Attributes["name"].Value;
zip.zip_code = Convert.ToInt32(xmlNode.Attributes["code"].Value);
dist.Zip.Add(zip);
zip = new Zip();
}
city.District.Add(dist);
dist = new District();
}
}
我能做到吗?
编辑 这是我的 AddressInfo 类。
[XmlRoot(ElementName = "AddressInfo")]
public class AddressInfo
{
[XmlElement(ElementName = "City")]
public List<City> City { get; set; }
public AddressInfo()
{
City = new List<City>();
}
}
这是我的城市课程。
[XmlRoot(ElementName = "City")]
public class City
{
public AddressInfo AddressInfo { get; set; }
[XmlAttribute(AttributeName = "name")]
public string city_name { get; set; }
[XmlAttribute(AttributeName = "code")]
public int city_code { get; set; }
[XmlElement(ElementName = "District")]
public List<District> District { get; set; }
public City()
{
District = new List<District>();
}
}
我想以给定的城市代码作为参数读取城市。并反序列化xml。