[英]XML Deserialization
我有以下xml文件。
<a>
<b>
<c>val1</c>
<d>val2</d>
</b>
<b>
<c>val3</c>
<d>val4</d>
</b>
<a>
我想將它反序列化為一個類,我想用創建的類的對象訪問它們。 我正在使用C#。 我能夠反序列化並將值放入類' a
'( <a>
標簽)的對象中。 但如何從這個對象訪問<b>
的值? 我做了以下編碼:
[Serializable()] [XmlRoot("a")] public class a { [XmlArray("a")] [XmlArrayItem("b", typeof(b))] public b[] bb{ get; set; } } [Serializable()] public class b { [XmlElement("c")] public string c{ get; set; } [XmlElement("d")] public string d{ get; set; } } class Program { static void Main(string[] args) { a i = null; string path = "test.xml"; XmlSerializer serializer = new XmlSerializer(typeof(a)); StreamReader reader = new StreamReader(path); i = (a)serializer.Deserialize(reader); reader.Close(); //i want to print all b tags here Console.Read(); } }
為此,您可以進行以下更改
public class a
{
[XmlElement("b")]
public b[] bb{ get; set; }
}
通過在數組上使用XmlElement
屬性,您實際上是在告訴序列化程序,數組元素應該序列化/反序列化為當前元素的直接子元素。
這是一個工作示例,我將XML放在一個字符串中只是為了使示例自包含。
using System;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
@"<a>
<b>
<c>val1</c>
<d>val2</d>
</b>
<b>
<c>val3</c>
<d>val4</d>
</b>
</a>";
XmlSerializer xs = new XmlSerializer(typeof(a));
a i = (a)xs.Deserialize(new StringReader(xml));
if (i != null && i.bb != null && i.bb.Length > 0)
{
Console.WriteLine(i.bb[0].c);
}
else
{
Console.WriteLine("Something went wrong!");
}
Console.ReadKey();
}
}
[XmlRoot("a")]
public class a
{
[XmlElement("b")]
public b[] bb { get; set; }
}
public class b
{
[XmlElement("c")]
public string c { get; set; }
[XmlElement("d")]
public string d { get; set; }
}
}
如果對創建xml序列化類有疑問,我發現解決問題的最簡單方法是:
我剛才在博客文章中寫了一篇快速教程: http : //www.diaryofaninja.com/blog/2010/05/07/make-your-xml-stronglytyped-because-you-can-and-its -簡單
它需要不到一分鍾,然后你可以輕松調整那里的東西。 XSD.exe是你的朋友
我發現解決問題的最簡單方法是將類a
和b
定義更改為以下內容
public class b {
public string c { get; set; }
public string d { get; set; }
}
[XmlRoot(Namespace="", ElementName="a")]
public class a : List<b> { }
然后你的程序將工作。 (可選)您可以向class b
添加屬性[XmlRoot (Namespace = "", ElementName = "b")]
class Program
{
static void Main(string[] args)
{
string employeedata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><tag><name>test</bar></nmae>";//demo xml data
using (TextReader sr = new StringReader(employeedata))
{
XmlSerializer serializer = new XmlSerializer(typeof(Employee));//pass type name in XmlSerializer constructor here
Employee response = (Employee)serializer.Deserialize(sr);
Console.WriteLine(response.name);
}
}
}
[System.Xml.Serialization.XmlRoot("tag")]
public class Employee
{
public string name { get; set; }
}
如果阻止(來自Chris Tyler的答案)改變如下。
if (i != null && i.bb != null && i.bb.Length > 0)
{
foreach (b t in i.bb)
{
Console.WriteLine(t.c);
Console.WriteLine(t.d);
}
}
然后它會給你以下結果:
val1 val2 val3 val4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.