如何将对象列表序列化为XML属性 [英] How do I serialize a list of objects as XML attributes
问题描述
你好,
我目前正在开发一个WPF应用程序项目,它允许我配置一个XML文件。此应用程序必须加载XML文件并允许用户动态更改属性值。
我尝试使用XmlSerializer对象,但其原生行为不匹配我需要做的事情。
想法是获取这样一个XML文件,其中包含一个未知数量的属性(属性的名称和数量来自另一个XML文件): br />
Hello there,
I'm currently working on a project of WPF application which allows me to configure a XML file. This application has to load a XML file and permit the user to dynamically change the attributes values.
I try to use the XmlSerializer object, but its native behavior doesn't match what I need to do.
The idea is to obtain such an XML file, with a non known number of attributes (the names and the number of attribute comes from an other XML file) :
<Parameters>
<elementOne attributeOne="ValueOne" attributeTwo="ValueTwo" ...attributeN="ValueN">
</elementOne>
</Parameters>
为了能够改变属性的数量,我创建了这样一个类,并且想法是实现IXmlSerializable,但我不知道如何,能够创建动态我的Xml文件中的属性列表:
In order to be able to change the number of attributes, I created such a Class, and the idea is to implement IXmlSerializable, but I don't know how, to be able to create a dynamic list of attributes in my Xml file :
public class element : IXmlSerializable
{
List<attribute> AttributeList;
public void WriteXml(XmlWriter writer)
{
???
}
}
你能否告诉我:
1)如果我想要的话是可能的。
2)如果我的方式很好
谢谢。
Could you tell me, please :
1)If what I want is possible.
2)If I'm on the good way
Thank you.
推荐答案
只需在循环中使用XMlElement类和xmlElement.setattribute()来处理这个....
Simply use XMlElement class and xmlElement.setattribute() in loop to take care of this....
所以...有一个解决方案
我们要做的很简单..
如果我们的类属性如下所示一:
So... There is a solution !
What we have to do is rather simple..
If our class Attribute looks like the following one :
{
public class Attribute
{
public Attribute(string name, int value)
{
this.Name = name;
this.Value = value;
}
public string Name;
public int Value;
}
}
解决方案可能是:
The solution could be :
public class element : IXmlSerializable
{
List<Attribute> AttributeList;
public void WriteXml(XmlWriter writer)
{
foreach(var attribute in AttributeList)
{
writer.WriteAttributeString(attribute.Name,attribute.Value.ToString());
}
}
}
结果是我在寻找什么。
And the result is what i was looking for.
这篇关于如何将对象列表序列化为XML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!