使用 xml 属性创建 XML 结构 [英] Creating XML structure using xml attributes
问题描述
我正在尝试使用 xml 属性解决一个难题.问题是我们已经广泛使用了这种结构的文件,我不能偏离
I am trying to solve a puzzle with xml attributes. The problem is that we already have widely used file with this structure, from which I can't deviate
<CONFIGS>
<CONFIG>
<NAME>c1</NAME>
<DB>
<VAL1>v1</VAL1>
<VAL2>v2</VAL2>
<VAL3>v3</VAL3>
</DB>
</CONFIG>
<CONFIG>
<NAME>c2</NAME>
<DB>
<VAL1>v1</VAL1>
<VAL2>v2</VAL2>
<VAL3>v3</VAL3>
</DB>
</CONFIG>
</CONFIGS>
我已经创建了这个 c# 代码
I've created this c# code
// master class
[XmlRoot(ElementName = "CONFIGS")]
public class MyConfigs
{
[XmlArrayItem(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
public MyConfigSchema[] Schemas { get; set; }
}
// I should have array of these
public class MyConfigSchema
{
[XmlElement(DataType = "string", ElementName = "NAME")]
public string Name { get; set; }
[XmlElement(ElementName = "DB", Type = typeof(Db))]
public Db Config { get; set; }
// this element is single and has subelements
public class Db
{
[XmlElement(DataType = "string", ElementName = "VAL1")]
public string Val1 { get; set; }
[XmlElement(DataType = "int", ElementName = "VAL2")]
public int Val2 { get; set; }
[XmlElement(DataType = "string", ElementName = "VAL3")]
public string Val3 { get; set; }
}
}
// Writing
using (var writer = new FileStream(testfile, FileMode.Create))
{
var ser = new XmlSerializer(typeof(MyConfigs));
ser.Serialize(writer, confFileObj);
writer.Close();
}
这是我的问题 - 它写了以下输出,这几乎是我需要的,但在那里写了 <Schemas>...</Schemas>
我不能拥有.
Here is my issue - it writes the following output, which is almost what I need but in there it writes <Schemas>. . . </Schemas>
that I can't have.
<代码><配置>--<架构>--<配置><NAME>c1</NAME><数据库><VAL1>v1</VAL1><VAL2>v2</VAL2><VAL3>v3</VAL3></DB></CONFIG><配置><NAME>c2</NAME><数据库><VAL1>v1</VAL1><VAL2>v2</VAL2><VAL3>v3</VAL3></DB></CONFIG>--</架构>--</CONFIGS>
有没有办法摆脱
?
推荐答案
看来我刚刚解决了.我以前从未见过这个,在 MSDN 上看过,因此我没有尝试.但我尝试代替这个
Looks like I just solved it. I have never seen this before, looked on MSDN, hence I didn't try it. But I tried instead of this
[XmlArrayItem(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
public MyConfigSchema[] Schemas { get; set; }
这样做
[XmlElement(ElementName = "CONFIG", Type = typeof(MyConfigSchema))]
public MyConfigSchema[] Schemas { get; set; }
我放置了 XmlElement
而不是 XmlArrayItem
并且它起作用了.我不知道可以用普通元素属性标记列表或数组.
Instead of XmlArrayItem
I placed XmlElement
and it worked. I didn't know one can mark List or array with plain element attribute.
这篇关于使用 xml 属性创建 XML 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!