如何解决如何反序列化xml文件的子节点
我使用 Xamarin Android 创建了一个应用。计划是从 Assets 文件夹打开 Clients.xml 的只读副本,并在内部存储中创建一个副本以供将来编辑。默认文件有一个客户端根节点和六个客户端子节点。
我已经到了读取资产并创建本地文件的地步,但只包含其中的第一个子节点。我无法将它传递到一系列子节点。
读取所有子节点需要做什么?
读取资产并创建本地文件。
// Get storage path
path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Create clients file on first build
string filename = System.IO.Path.Combine(path,"Clients.xml");
if (!File.Exists(filename))
{
clients clients;
// Load read-only asset from file
var xmlSerialSettings = new XmlSerializer(typeof(clients));
using (StreamReader sr = new StreamReader(Android.App.Application.Context.Assets.Open("Clients.xml"),true))
{
clients = (clients)xmlSerialSettings.Deserialize(sr);
}
// Save local version to edit
var xsw = new XmlSerializer(typeof(clients));
using (StreamWriter sw = new StreamWriter(filename,false))
{
xsw.Serialize(sw,clients);
}
}
客户端.xml
<?xml version="1.0" encoding="utf-8" ?>
<clients>
<client id="1">
<name>Bob</name>
<address>Home</address>
<postcode>CO1</postcode>
<email>bob@home.com</email>
<landline></landline>
<mobile>07784</mobile>
</client>
<client id="2">
<name>...</name>
<address>...</address>
<postcode>...</postcode>
<email>...</email>
<landline>...</landline>
<mobile>...</mobile>
</client>
....
</clients>
Clients.cs
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace QuoteBuilder
{
[Serializable,XmlRoot("clients")]
public class clients
{
[XmlElement("client")]
public client client { get; set; }
public clients()
{
}
public clients(client client)
{
this.client = client;
}
}
public class client
{
public string name { get; set; }
public string address { get; set; }
public string postcode { get; set; }
public string email { get; set; }
public string landline { get; set; }
public string mobile { get; set; }
public client()
{
}
public client(string name,string address,string postcode,string email,string landline,string mobile)
{
this.name = name;
this.address = address;
this.postcode = postcode;
this.email = email;
this.landline = landline;
this.mobile = mobile;
}
}
}
解决方法
在您的客户类中,您定义了一个成员 - 客户。它不是一个集合,当您将 xml 文件反序列化为客户端类时,它只会反序列化一个节点(第一个)。 在里面使用 List 或其他集合:
[Serializable,XmlRoot("clients")]
public class Clients
{
[XmlElement("client")]
public List<Client> client { get; set; } // Collection
public Clients()
{
}
public Clients(List<Client> client)
{
this.client = client;
}
}
类也使用驼峰命名,变量使用小写命名 - 更易读
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。