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
相关文档:
--A. 从存储在非类型化的 xml 变量中的文档中删除节点
DECLARE @myDoc xml
SET @myDoc = '<?Instructions for=TheWC.exe ?>
<Root>
<!-- instructions for the 1st work center -->
<Location LocationID="10" LaborHours="1.1" MachineHours=".2" >
Some text 1
<st ......
XML 命名空间提供了一种避免元素命名冲突的方法。
--------------------------------------------------------------------------------
命名冲突
因为XML文档中使用的元素不是固定的,那么两个不同的XML文档使用同一个名字来描述不同类型的元素的情况就可能发生。而这种情况又往往会导致命名冲突。请看下面两个例子
......
XML 命名空间提供了一种避免元素命名冲突的方法。
命名空间属性一般放置在元素的开始标记处,其使用语法如下所示:
xmlns:namespace-prefix="namespace",
例如:xmlns:f="http://www.w3schools.com/furniture"
W3C 命名规范声明命名空间本身就是一个统一资源标示符,Uniform Resource Identifier (URI)。
asp.net读取X ......
1 防止sql注入式攻击(可用于UI层控制) #region 防止sql注入式攻击(可用于UI层控制)
2
3 /**/ ///
4 /// 判断字符串中是否有SQL攻击代码
5 ///
6 /// 传入用户提交数据
7 /// ......