一: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)