如何使用xml创建c#对象 [英] How to create c# objects using xml
问题描述
我是 C#、Silverlight 5 和 XAML 初学者.我正在做一个 VS-2012 项目,我不需要使用任何 CycleClip Board Ring 来完成这个任务.我的 VS 项目中有一个 XML 文件.假设文件如下:
I am new to C#, Silverlight 5 and XAML beginner. I am working on a VS-2012 project and I don't have to use any CycleClip Board Ring to do this task. I have an XML file in my VS project. Suppose the file is given below:
FileName is FileXml.xml
<?xml version="1.0" encoding="utf-8" ?>
<parameter>
<name>mounts</name>
<unit></unit>
<component>
<type>List</type>
<attributes>
<type>Integer</type>
<displayed>4</displayed>
<add_remove>yes</add_remove>
<item>25</item>
</attributes>
<attributes>
<ccypair>XAUUSD</ccypair>
<item>100</item>
</attributes>
</component >
</parameter>
而且我必须解析这个 XML 文件,并且必须在 C# 中创建对象.这样我就可以使用bands_amounts"(名称)和通过这些对象访问的所有其他元素.如何使用 C# 代码执行此操作?
And I have to parse this XML file and have to create the object in C# .So that I would be able to use "bands_amounts" (name) and all other elements accessing through those objects. How to do this using C# code?
推荐答案
您将需要使用某种反序列化.这是我不久前实施的一个示例:
You will want to use some sort of de-serialization. Here is an example of one I implemented not too long ago:
public static class Serialization<T> where T : class
{
public static T DeserializeFromXmlFile(string fileName)
{
if (!File.Exists(fileName))
{
return null;
}
DataContractSerializer deserializer = new DataContractSerializer(typeof(T));
using (Stream stream = File.OpenRead(fileName))
{
return (T)deserializer.ReadObject(stream);
}
}
}
然后调用它你会做这样的事情:
Then to call it you would do something like this:
Serialization<YourCustomObject>.DeserializeFromXmlFile(yourFileNameOrPath);
请记住,您必须有一个与要反序列化的 XML 相对应的类.(也就是变成一个物体).
Remember that you would have to have a Class that corresponds to the XML you want to de-serialized. (aka turn into an object).
你的类看起来像这样:
[Serializable]
class parameter
{
[Datamember]
public string name {get; set;}
[Datamember]
public string label {get; set;}
[Datamember]
public string unit {get; set;}
[Datamember]
public component thisComponent {get; set;}
}
[Serializable]
class component
{
[Datamember]
public string type {get; set;}
[Datamember]
public List<attribute> attributes {get; set;}
}
[Serializable]
class attribute
{
[Datamember]
public string? type {get; set;}
[Datamember]
public string? displayed {get; set;}
[Datamember]
public string? add_remove {get; set;}
[Datamember]
public string? ccypair {get; set;}
[Datamember]
public List<int> item { get; set;}
}
这篇关于如何使用xml创建c#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!