I want to create the following xml:
<StartLot>
<fileCreationDate level="7">201301132210</fileCreationDate>
<fmtVersion level="7">3.0</fmtVersion>
</StartLot>
Below is the Serialization code:
[Serializable]
class StartLot
{
public fileCreationDate{get; set;}
[XmlAttribute("level")]
public string level = "7";
public fmtVersion{get; set;}
[XmlAttribute("level")]
public string level = "7"; ??
}
Since I already declared attribute level, how do I add the last attribute?
You can use a wrapped class to store both values, as in the example below:
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);
}
}
I always find Linq To Xml
easier to use
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.