[英]How to deserialize child nodes of xml file
我使用 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>
客户端.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;
}
}
}
在您的客户 class 中,您定义了一个成员 - 客户。 它不是一个集合,当您将 xml 文件反序列化到客户端 class 时,它只反序列化一个节点(第一个)。 使用 List 或其他 collections 里面:
[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;
}
}
还对类使用 CamelCase 命名,对变量使用小写命名 - 它更具可读性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.