C#序列化xml的完整例子
C#序列化xml
关键步骤:
XmlSerializer xSerializer = new XmlSerializer(typeof(MyObj));
StringWriter sWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlTextWriter xTextWriter = new XmlTextWriter(sWriter);
XmlDocument xmlDoc = new XmlDocument();
xSerializer.Serialize(xTextWriter, myObj);
xmlDoc.LoadXml(sWriter.ToString());
需要说明的是,如果要序列化的object所在的类里有带参数的构造函数,还必须添加一个无参数的构造函数,否则,会报object cannot be serialized because it does not have a parameterless constructor的错误。下面是一个完整的实例,仅供参考。
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
/* The XmlRootAttribute allows you to set an alternate name
(PurchaseOrder) of the XML element, the element namespace; by
default, the XmlSerializer uses the class name. The attribute
also allows you to set the XML namespace for the element. Lastly,
the attribute sets the IsNullable property, which specifies whether
the xsi:null attribute appears if the class instance is set to
a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
/* The XmlArrayAttribute changes the XML element name
from the default of "OrderedItems" to "Items". */
[XmlArrayAttribute("Items")]
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}
public class Address
{
/* The XmlAttribute instructs the XmlSerializer to serialize the Name
field as an XML attribute instead of an XML element (the default
behavior). */
[XmlAttribute]
public string Name;
public string Line1;
/* Setting the IsNull
相关文档:
如何在VC环境下编写程序读取XML文件?清提供源代码.谢谢.
#import <msxml3.dll> named_guids //导入动态库,装了IE5就有
using namespace MSXML2; //引用命名空间,一般可以把命名空间理解成类和接口的集合,呵呵,对不对我也不知道了
#include <vector>
using na ......
/*
* 主要作用;
* 从xml读取游戏配置信息或保存
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Reflection;
namespace Game
{
class Config
{
Ke ......
protected void BindData1()
{
OracleConnection orcn = new OracleConnection("User ID=wesoftwcp; Password=wesoft; Data Source=oradb");
orcn.Open();
&nb ......
不得不自已写一个.XML
的操作一直没有用过.下面是自己搜集的XML操作类
DOMDocument相关的内容.
属性:
Attributes 存储节点的属性列表(只读)
childNodes
存储节点的子节点列表(只读)
dataType 返回此节点的数据类型
Definition 以DTD或XML模式给出的节点的定义(只读)
Doctype 指定文档类型节点(只读)
doc ......