我有下一个xml:
<table-display-fields>
<field name="NAME/>
<field name="DESCRIPTION" />
</table-display-fields>
我用下一个代码实现了这个目标:
[XmlArray("table-display-fields")]
[XmlArrayItem("field")]
public TableDisplayField[] TableDisplayFields;
然后我将新的xml元素添加到table-display-fields节点:
<table-display-fields>
<record-number-field name="ID" />
<field name="NAME/>
<field name="DESCRIPTION" />
</table-display-fields>
然后添加下一个代码来deserealize record-number-field:
[XmlArray("table-display-fields")]
[XmlArrayItem("record-number-field")]
public TableDisplayField[] RecordTableDisplayFields;
[XmlArray("table-display-fields")]
[XmlArrayItem("field")]
public TableDisplayField[] TableDisplayFields;
这不起作用。如何取消实现新的xml,并保存现有的属性路径?
答案 0 :(得分:1)
您必须删除XmlArrayItem()属性。
[XmlArray("table-display-fields")]
public object[] TableDisplayItems;
TableDisplayItems
中的每个对象都是field
或record-number-field
。
当然,如果您的阵列上只有一个record-number-field
,那么解决方案可以更好。是这样的吗?
答案 1 :(得分:0)
如果您能够对您的要求进行更详细的描述,那么将会有所帮助。如果您正在寻找正常的序列化/反序列化,您可以尝试以下解决方案:
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Serialization01 {
[XmlRoot( "table-display-fields" )]
public class TableDisplayFields {
[XmlElement( "record-number-field" )]
public string RecordNumberField { get; set; }
[XmlElement( "field" )]
public List<string> FieldName { get; set; }
public TableDisplayFields ( ) {
FieldName = new List<string>( 5 );
}
}
}
并使用以下代码编写和读取序列化数据:
using System.IO;
using System.Xml.Serialization;
using System;
namespace Serialization01 {
class Program {
static void Main ( string [] args ) {
// Initiate the class
TableDisplayFields t = new TableDisplayFields( );
t.RecordNumberField = "ID";
t.FieldName.Add( "NAME" );
t.FieldName.Add( "DESCRIPTION" );
TextWriter tw = new StreamWriter( Path.Combine( Environment.CurrentDirectory, "Data.xml" ) );
XmlSerializer xs = new XmlSerializer( t.GetType( ) );
xs.Serialize( tw, t );
tw.Flush( );
tw.Close( );
TextReader tr = new StreamReader( Path.Combine( Environment.CurrentDirectory, "Data.xml" ) );
TableDisplayFields t2 = xs.Deserialize( tr ) as TableDisplayFields;
Console.WriteLine( "RecordNumberField for t2 is {0}", t2.RecordNumberField );
foreach ( string field in t2.FieldName ) {
Console.WriteLine( "Found field '{0}'", field );
}
}
}
}
希望有所帮助。