C#实体类生成XML与XML Schema文档

Posted 超人不会敲代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#实体类生成XML与XML Schema文档相关的知识,希望对你有一定的参考价值。

一、实体类生成XML

 1 private void CreateXML()
 2         {
 3             Type[] objType = DBEntityRegst();
 4             foreach (var item in objType)
 5             {
 6                 if (item == null)
 7                 {
 8                     break;
 9                 }
10 
11                 XmlDocument doc = new XmlDocument();
12 
13                 //<?xml version="1.0"?>
14                 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "", "");
15                 doc.AppendChild(dec);
16 
17                 //创建一个根节点
18                 //<schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
19                 XmlElement root = doc.CreateElement("schema");
20                 root.SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
21                 doc.AppendChild(root);
22 
23                 //<element Name="DTO_BatchTotal">
24                 XmlElement element1 = doc.CreateElement("element");
25                 element1.SetAttribute("Name", (item.Name).ToString());
26 
27                 //<complexType>
28                 XmlElement element2 = doc.CreateElement("complexType");
29 
30                 //<sequence>
31                 XmlElement element3 = doc.CreateElement("sequence");
32 
33 
34                 System.Reflection.PropertyInfo[] ps = item.GetProperties();
35                 for (int i = 0; i < ps.Length; i++)
36                 {
37                     string typeold = (ps[i].PropertyType).ToString();
38                     string[] a = typeold.Split(\'.\');
39                     string typenew = ("xs:" + a[1]).ToLower();
40 
41                     //<element Name="batch" Type="xs:string" />
42                     //<element Name="total" Type="xs:decimal" />
43                     XmlElement element4 = doc.CreateElement("element");
44                     element4.SetAttribute("Name", ps[i].Name);
45                     element4.SetAttribute("Type", typenew);
46 
47                     //给element3添加子节点
48                     element3.AppendChild(element4);
49                 }
50                 //同上
51                 element1.AppendChild(element2);
52                 element2.AppendChild(element3);
53                 root.AppendChild(element1);
54 
55                 XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
56                 xsn.Add("xs", "http://www.w3.org/2001/XMLSchema");
57                 doc.Save(@"E:\\XML\\" + item.Name.ToString() + ".xml");
58 
59 
60             }
61         }
62 
63         /// <summary>
64         /// 将DTO实体加载到List列表
65         /// </summary>
66         private Type[] DBEntityRegst()
67         {
68 
69             List<IEntityRegstHelper> entityRegstHelperlist = null;
70             entityRegstHelperlist = new List<IEntityRegstHelper>();
71             var classes = Assembly.Load("ZxSoftERPGC.Model").GetTypes();//命名空间[Model]下的类类型集
72 
73             Type[] a = new Type[classes.Length];
74             int i = 0;
75             foreach (var classtype in classes)
76             {
77 
78                 if (((classtype.Name).ToString()).Contains("DTO_")) //指定获取类名包含“DTO_”的类
79                 {
80                     a[i] = classtype;
81                     i++;
82                 }
83             }
84             return a;
85         }

结果如:

<?xml version="1.0"?>
<schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <element Name="DTO_BatchTotal">
    <complexType>
      <sequence>
        <element Name="batch" Type="xs:string" />
        <element Name="total" Type="xs:decimal" />
      </sequence>
    </complexType>
  </element>
</schema>

 

 

参考:http://www.cnblogs.com/xwdreamer/archive/2011/04/27/2297023.html

 

二、生成XML Schema

 private void button1_Click(object sender, EventArgs e)
        {
            Type[] objType = DBEntityRegst();
            foreach (var item in objType)
            {
                if (item == null)
                {
                    break;
                }

                XmlSchema schema = new XmlSchema();

                // <xs:element name="">
                XmlSchemaElement elementPets = new XmlSchemaElement();
                schema.Items.Add(elementPets);
                elementPets.Name = (item.Name).ToString();

                // <xs:complexType>
                XmlSchemaComplexType complexType = new XmlSchemaComplexType();
                elementPets.SchemaType = complexType;

                //<xs:sequence>
                XmlSchemaSequence seqauth = new XmlSchemaSequence();
                complexType.Particle = seqauth;

                System.Reflection.PropertyInfo[] ps = item.GetProperties();
                for (int i = 0; i < ps.Length; i++)
                {
                    // <xs:element name=""/>
                    XmlSchemaElement catRef = new XmlSchemaElement();
                    seqauth.Items.Add(catRef);
                    catRef.Name = ps[i].Name;
                    string typeold = (ps[i].PropertyType).ToString();
                    string[] a = typeold.Split(\'.\');
                    string typenew = (a[1]).ToLower();
                    //类型格式转换
                    if (typenew == "int32" || typenew == "int64")
                    {
                        typenew = "integer";
                    }
                    if (typenew == "datetime")
                    {
                        typenew = "date";
                    }
                    catRef.SchemaTypeName = new XmlQualifiedName(typenew, "http://www.w3.org/2001/XMLSchema");
                }

                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add(schema);
                schemaSet.Compile();

                XmlSchema compiledSchema = null;

                foreach (XmlSchema schema1 in schemaSet.Schemas())
                {
                    compiledSchema = schema1;
                }
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
                nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

                //用流的形式输出保存
                using (MemoryStream stream = new MemoryStream())
                {
                    compiledSchema.Write(stream, nsmgr);
                    FileStream fs = new FileStream(@"E:\\XML\\" + item.Name.ToString() + ".xml", FileMode.Create);
                    BinaryWriter w = new BinaryWriter(fs);
                    w.Write(stream.ToArray());
                    fs.Close();
                    stream.Close();
                }


            }
        }

结果如:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="DTO_BatchTotal">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="batch" type="xs:string" />
        <xs:element name="total" type="xs:decimal" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

参考:https://msdn.microsoft.com/en-us/library/system.xml.schema.xmlschema(v=vs.110).aspx

 

2种生成都是用实体集批量生成,单个实体就不用演示了吧。

 

以上是关于C#实体类生成XML与XML Schema文档的主要内容,如果未能解决你的问题,请参考以下文章

如何使生成的类包含 XML Schema 文档中的 Javadoc

xml约束技术---schema

在C++中如何用schema校验xml文件

C#实体类与XML相互转换

C# XML和实体类之间相互转换(序列化和反序列化)

xml