.NET XML序列化
我正在研究将用于序列化为XML的一组类。 XML不受我的控制,组织得很好。不幸的是,有几组嵌套节点,其中一些嵌套节点的目的只是为了保存其子级集合。根据我目前对XML序列化的了解,这些节点需要另一个类。
有没有一种方法可以使一个类序列化到一组XML节点而不是一个。因为我感觉自己像泥一样清澈,所以说我们有xml:
<root> <users> <user id=""> <firstname /> <lastname /> ... </user> <user id=""> <firstname /> <lastname /> ... </user> </users> <groups> <group id="" groupname=""> <userid /> <userid /> </group> <group id="" groupname=""> <userid /> <userid /> </group> </groups> </root>
理想情况下,最好是3节课。与用户
和组
对象的集合的类根
。但是,我能想到的是,我需要一个用于root,users,user,groups和group的类,其中users和groups仅包含user和user的集合。组和根分别包含一个用户和组对象。
有谁比我更了解? (不要说谎,我知道有)。
解决方案
回答
我们不使用XmlSerializer吗?这真是太好了,并且使做这样的事情变得非常容易(我经常使用它!)。
我们可以简单地用一些属性装饰类属性,其余的一切都为我们完成。
我们是否考虑过使用XmlSerializer或者是否有特定的原因?
以下是获得上述内容进行序列化的所有工作的代码片段(两种方式):
[XmlArray("users"), XmlArrayItem("user")] public List<User> Users { get { return _users; } }
回答
我们只需要将"用户"定义为"用户"对象的数组即可。 XmlSerializer将为我们适当地呈现它。
有关示例,请参见此链接:
http://www.informit.com/articles/article.aspx?p=23105&seqNum=4
此外,按照http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization,我建议使用Visual Studio生成XSD,并使用命令行实用程序XSD.EXE为我们吐出类层次结构。 /XSDToCls.aspx
回答
我回想起当初写的这节课来做我想做的事情,类似于我们要尝试做的事情。我们将在希望序列化为XML的对象上使用此类的方法。例如,给一个雇员...
使用实用程序;
使用System.Xml.Serialization;
[XmlRoot(" Employee")]
公职员工
{
private String name ="史蒂夫";
[XmlElement("Name")] public string Name { get { return name; } set{ name = value; } } public static void Main(String[] args) { Employee e = new Employee(); XmlObjectSerializer.Save("c:\steve.xml", e); }
}
此代码应输出:
<Employee> <Name>Steve</Name> </Employee>
对象类型(员工)必须可序列化。试试[Serializable(true)]。
我在某个地方有一个更好的代码版本,我只是在编写时学习。
无论如何,请查看下面的代码。我在某些项目中使用它,因此它一定可以正常工作。
using System; using System.IO; using System.Xml.Serialization; namespace Utilities { /// <summary> /// Opens and Saves objects to Xml /// </summary> /// <projectIndependent>True</projectIndependent> public static class XmlObjectSerializer { /// <summary> /// Serializes and saves data contained in obj to an XML file located at filePath <para></para> /// </summary> /// <param name="filePath">The file path to save to</param> /// <param name="obj">The object to save</param> /// <exception cref="System.IO.IOException">Thrown if an error occurs while saving the object. See inner exception for details</exception> public static void Save(String filePath, Object obj) { // allows access to the file StreamWriter oWriter = null; try { // Open a stream to the file path oWriter = new StreamWriter(filePath); // Create a serializer for the object's type XmlSerializer oSerializer = new XmlSerializer(obj.GetType()); // Serialize the object and write to the file oSerializer.Serialize(oWriter.BaseStream, obj); } catch (Exception ex) { // throw any errors as IO exceptions throw new IOException("An error occurred while saving the object", ex); } finally { // if a stream is open if (oWriter != null) { // close it oWriter.Close(); } } } /// <summary> /// Deserializes saved object data of type T in an XML file /// located at filePath /// </summary> /// <typeparam name="T">Type of object to deserialize</typeparam> /// <param name="filePath">The path to open the object from</param> /// <returns>An object representing the file or the default value for type T</returns> /// <exception cref="System.IO.IOException">Thrown if the file could not be opened. See inner exception for details</exception> public static T Open<T>(String filePath) { // gets access to the file StreamReader oReader = null; // the deserialized data Object data; try { // Open a stream to the file oReader = new StreamReader(filePath); // Create a deserializer for the object's type XmlSerializer oDeserializer = new XmlSerializer(typeof(T)); // Deserialize the data and store it data = oDeserializer.Deserialize(oReader.BaseStream); // // Return the deserialized object // don't cast it if it's null // will be null if open failed // if (data != null) { return (T)data; } else { return default(T); } } catch (Exception ex) { // throw error throw new IOException("An error occurred while opening the file", ex); } finally { // Close the stream oReader.Close(); } } } }