我想创建以下xml:
<StartLot>
<fileCreationDate level="7">201301132210</fileCreationDate>
<fmtVersion level="7">3.0</fmtVersion>
</StartLot>
以下是序列化代码:
[Serializable]
class StartLot
{
public fileCreationDate{get; set;}
[XmlAttribute("level")]
public string level = "7";
public fmtVersion{get; set;}
[XmlAttribute("level")]
public string level = "7"; ??
}
由于我已经声明了属性级别,我该如何添加最后一个属性?
答案 0 :(得分:2)
您可以使用包装类来存储这两个值,如下例所示:
public class StackOverflow_15441384
{
const string XML = @"<StartLot>
<fileCreationDate level=""7"">201301132210</fileCreationDate>
<fmtVersion level=""7"">3.0</fmtVersion>
</StartLot>";
public class StartLot
{
[XmlElement("fileCreationDate")]
public LevelAndValue FileCreationDate { get; set; }
[XmlElement("fmtVersion")]
public LevelAndValue FmtVersion { get; set; }
}
public class LevelAndValue
{
[XmlAttribute("level")]
public string Level { get; set; }
[XmlText]
public string Value { get; set; }
}
public static void Test()
{
XmlSerializer xs = new XmlSerializer(typeof(StartLot));
StartLot sl = (StartLot)xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(XML)));
Console.WriteLine("FCD.L = {0}", sl.FileCreationDate.Level);
Console.WriteLine("FCD.V = {0}", sl.FileCreationDate.Value);
Console.WriteLine("FV.L = {0}", sl.FmtVersion.Level);
Console.WriteLine("FV.V = {0}", sl.FmtVersion.Value);
}
}
答案 1 :(得分:0)
我总觉得Linq To Xml
更容易使用
var xDoc = XDocument.Parse(xml); /* XDocument.Load(filename); */
var items = xDoc.Root.Descendants()
.Select(e => new
{
Name = e.Name.LocalName,
Level = e.Attribute("level").Value,
Value = e.Value
})
.ToList();