我试图用xml覆盖来做事,但我做对了。
生成输出的示例代码
这是示例代码:
public class TestXml
{
public TestXmlElement[] testXmlArray = new TestXmlElement[] { new TestXmlElement(),new TestXmlElement() };
public TestXml() { }
}
public class TestXmlElement
{
[XmlAttribute]
public string Name = "default";
[XmlAttribute]
public ulong Value = 1;
public TestXmlElement() { }
}
class Program
{
static void Main(string[] args)
{
TestXml tx=new TestXml();
StreamWriter sw=new StreamWriter(@"g:\test_class.xml");
XmlSerializer x = new XmlSerializer(typeof(TestXml));
x.Serialize(sw.BaseStream, tx);
sw.Close();
TestXmlElement[] txa = new TestXmlElement[] { new TestXmlElement(),new TestXmlElement() };
sw = new StreamWriter(@"g:\test_array.xml");
x = new XmlSerializer(typeof(TestXmlElement[]));
x.Serialize(sw.BaseStream, txa);
sw.Close();
}
}
输出
这就是test_class.xml中的内容
<?xml version="1.0"?>
<TestXml>
<testXmlArray>
<TestXmlElement Name="default" Value="1" />
<TestXmlElement Name="default" Value="1" />
</testXmlArray>
</TestXml>
这就是test_array.xml中的内容
<?xml version="1.0"?>
<ArrayOfTestXmlElement>
<TestXmlElement Name="default" Value="1" />
<TestXmlElement Name="default" Value="1" />
</ArrayOfTestXmlElement>
预期输出
这就是我需要的(如果由类使用,则没有数组层;如果编写数组本身,则没有重写数组标识符):
(如果在类情况下不存在数组层,那么我可以正确地命名该类没有问题。编写类的问题是
<?xml version="1.0"?>
<SOME_OVERRIDDEN_NAME>
<TestXmlElement Name="default" Value="1" />
<TestXmlElement Name="default" Value="1" />
</SOME_OVERRIDDEN_NAME>
答案 0 :(得分:2)
您可以将TestXml
类创建为IList<TestXmlElement>
实现:
[XmlRoot(ElementName = "SOME_OVERRIDDEN_NAME")]
public class TestXml : IList<TestXmlElement>
{
private List<TestXmlElement> _innerList = new List<TestXmlElement>();
public TestXmlElement this[int index] { get => _innerList[index]; set => _innerList[index] = value; }
public int Count => _innerList.Count;
public bool IsReadOnly => false;
-- snip rest of IList members
}
然后:
class Program
{
static void Main(string[] args)
{
TestXml tx = new TestXml();
tx.Add(new TestXmlElement());
tx.Add(new TestXmlElement());
StreamWriter sw = new StreamWriter(@"c:\temp\testproj\test_class.xml");
XmlSerializer x = new XmlSerializer(typeof(TestXml));
x.Serialize(sw.BaseStream, tx);
sw.Close();
}
}
结果:
<?xml version="1.0"?>
<SOME_OVERRIDDEN_NAME xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TestXmlElement Name="default" Value="1" />
<TestXmlElement Name="default" Value="1" />
</SOME_OVERRIDDEN_NAME>