好的我正在使用ASP MVC并且正在尝试加载一些我需要序列化的XML数据,因为我将它转换为JSON。
我无法理解的是,我的XML有多个后代。那么,当我序列化它时,在模型中我需要将每个后代的数据存储在它自己的列表中吗?
我已经做到了,所以我有两个单独的名单。那么,我如何将这一切都序列化为一个XML文档?
这是我的XML标记的一个例子:
<vehicle>
<make>Suzuki</make>
<color>Yellow></color>
<owner>
<id>0</id>
<name>Joe Bloggs</name>
</owner>
<owner>
<id>1</id>
<name>Foo Bar</name>
</owner>
</vehicle>
这是我的XML模型:
public partial class vehicle
{
private string makeField;
private string colorField;
private vehicleOwner[] ownerField;
/// <remarks/>
public string make {get; set;}
/// <remarks/>
public string color{get; set;}
[System.Xml.Serialization.XmlElementAttribute("owner")]
public vehicleOwner[] owner{ get; set;}
// Keep this in a list to serialize it
List<vehicle> vehicleList = new List<vehicle>();
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class vehicleOwner
{
private int idField;
private string nameField;
/// <remarks/>
public int id { get; set;}
/// <remarks/>
public string nameField {get; set;}
// Stick it in a list so I can serialize it later
List<vehicleOwner> vehicleOwnerList = new List<vehicleOwner>();
}
}
所以,现在我有两个包含XML数据的列表:vehicleOwnerList和vehicleList。 但这些都是一个XML文档。那么如何为两个列表序列化这个?我是否必须将它们合并到一个列表中,如果是这样,我该怎么做?
所以I.E。
List<vehicleOwner> listCombinedActions = new List<vehicleOwner>();
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<vehicle>), new XmlRootAttribute("owner"));
ser.Serialize(writer, listCombinedActions);
}
干杯
答案 0 :(得分:1)
我希望我明白你想要实现的目标,这样可以添加如何完成的例子:
数据模型:
//NOTE: property, root class names is different.
//So you can name it what you want but you need to specify xml tag name in attribute
[XmlRoot("vehicle")]
public class vehicleObject
{
public string make { get; set; }
public string color { get; set; }
[System.Xml.Serialization.XmlElement("owner")]
public List<vehicleOwner> ownerList { get; set; }
}
public class vehicleOwner
{
public int id { get; set; }
[System.Xml.Serialization.XmlElement("name")]
public string nameField { get; set; }
}
用法:
vehicleObject yourWorkingObject;
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes("c:\\a.xml")))
{
XmlSerializer serializer = new XmlSerializer(typeof(vehicleObject));
yourWorkingObject = serializer.Deserialize(ms) as vehicleObject;
}
//Do with yourWorkingObject here what you want
结果: