標籤:
一:C#產生XML,其元素或屬性由類的定義來設定(xml序列化)
將一個字串轉到一個XML文檔中的xmlAttribute或xmlElement
using System;System.xml.Serialization;
namespace xmlserializa
{
1.初始化一個類,設定屬性值
[XmlRoot("Truck")] ----設定作為XML中的根項目名稱 public Truck() { } [XmlAttribute("id")] --------設定作為xml中的屬性 public int ID { get{return this._id;} set { this._id = value; } } [XmlElement("chepai")]------設定作為XML中的元素(預設狀態) public string cheID { get { return this._cheID; } set { this._cheID = value; } } private int _id = 0; private string _cheID = ""; }
class Program { [STAThread] static void Main(string[] args) {
2.建立XmlSerializer執行個體
XmlSerializer ser = new XmlSerializer(Type.GetType("ConsoleApplication1.Truck")); Truck tr = new Truck(); tr.ID = 1; tr.cheID = "贛A T34923";
3.Serialize方法--完成對類的序列化 ser.Serialize(Console.Out, tr);
}
}
個人總結,這個可以用來在C#中對XML的產生。
二:C#產生XSD規範,利用XmlSchema類
1。xsd基礎:
類型:xs:integer; xs:positiveInteger;(>0的整數); xs:nonPositiveInteger;(<=0的整數); xs:Bool; xs:string xs:dateTime;(日+時); xs:date;(日); xs:time;(時);
<xs:schema....>
<xs:complexType name="autotype">------2級 <xs:sequence> <xs:element name="name" type="xs:string"/>-----1級 </xs:sequence> </xs:complexType>
<xs:complexType name="booktype">-----3級 <xs:sequence> <xs:element name="typename" type="autotype"/>------應用2級 </xs:sequence> </xs:complexType>
<xs:element name="book" type="booktype"/>-----應用3級
</xs:schema>
2。設計成XML模式
class Program { [STAThread] static void Main(string[] args) { XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable()); nsm.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); XmlSchema sche = new XmlSchema(); XmlSchemaComplexType cauth = new XmlSchemaComplexType(); cauth.Name = "author"; XmlSchemaSequence seqauth = new XmlSchemaSequence(); XmlSchemaElement ele = new XmlSchemaElement(); ele.Name = "name"; ele.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); seqauth.Items.Add(ele); XmlSchemaElement eleage = new XmlSchemaElement(); eleage.Name = "age"; eleage.SchemaTypeName = new XmlQualifiedName("positiveInteger", "http://www.w3.org/2001/XMLSchema"); seqauth.Items.Add(eleage); cauth.Particle = seqauth; sche.Items.Add(cauth); sche.Compile(new ValidationEventHandler(valia)); sche.Write(Console.Out, nsm); } }
個人總結:
結果:
<?xml version="1.0" encoding="gb2312"?> ----------------xs:..........->xmlNamespaceManager.AddNamespace <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">-new XmlSchema <xs:complexType name="author">------------------new XmlSchemaComplexType <xs:sequence>----------------------------------new XmlSchemaSequence <xs:element name="name" type="xs:string"/>---new XmlSchemaElement <xs:element name="age" type="xs:positiveInteger"/>------new XmlSchemaElement </xs:seqence> </xs:complexType> </xs:schema>
XmlSchema.Items.Add(XmlSchemaComplexType) XmlSchemaComplexType.Particle = XmlSchemaSequence XmlSchemaSequence.Add(XmlSchemaElement)
http://blog.sina.com.cn/s/blog_5d77d3390100btr4.html
C#產生XSD規範