1. 程式人生 > >xml XMLSchema(xsd)的學習體會以及XML格式化和驗證總結

xml XMLSchema(xsd)的學習體會以及XML格式化和驗證總結

自己學習和使用xml作為定義語言已經有一段時間了,隨著自己xml定義的複雜性增長,對於能實現vs2010中的程式碼提示和驗證很是嚮往。

上週接觸到XMLSchema可以解決自己的困惑,經過一週的努力終於把自己的xml定義的程式碼提示和驗證搞定了,非常感謝網友的共享和文章,自己總結下來作為回報吧。

1、xml定義

<?xml version="1.0" encoding="utf-8"?>
<root>
  <myquery title="匯入員工資料" isvisible="true">
    <url>tmp/MyImport.aspx?n=importhbinfo1&amp;m=d</url>
  </myquery>
</root>

2、XMLSchema(利用vs2010開啟,在xml選單下可以根據你的xml生成XMLSchema)

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="myquery">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="url" type="xs:string" />
            </xs:sequence>
            <xs:attribute name="title" type="xs:string" use="required" />
            <xs:attribute name="isvisible" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

3、擴充套件上面的XMLSchema讓他更符合自己的需求(就不多做解釋了,大家一看就能明白,不理解就google下吧)

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"

<!--加入自己的名稱空間-->
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element  minOccurs="1" maxOccurs="unbounded" name="myquery">
          <xs:complexType>
            <xs:sequence>
              <xs:element minOccurs="1" maxOccurs="unbounded"  name="url" type="urltype" />
            </xs:sequence>
            <xs:attribute name="title" type="xs:string" use="required" />
            <xs:attribute name="isvisible" type="logicvalue" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

<!--定義自己的型別-->
  <xs:simpleType name="urltype">
    <xs:restriction base="xs:string">
      <xs:pattern value="(http://)?([\w-]+\.)*[\w-]*(/?[_\w-./?%&amp;=]*)?"></xs:pattern>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="logicvalue">
    <xs:restriction base="xs:string">
      <xs:enumeration value="false" />
      <xs:enumeration value="true" />
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

這樣上面的xml中

就可以了在vs2010中實現提示和自動驗證了。

4、C#程式碼驗證

        private static string msgCheck = null;
        /// <summary>
        /// 根據Demo.xsd校驗 xml檔案或字串
        /// </summary>
        /// <param name="xml">xml的檔案必須以.xml結尾 或 xml的字串</param>
        /// <returns></returns>
        public static string CheckXmlContent(string xml)
        {
            // 初始化出錯資訊
            msgCheck = String.Empty;
            try
            {
                string xsdFile = WebHelper.GetMyXmlPath() + "\\Demo.xsd";   // xsd架構文件
                if (File.Exists(xsdFile))
                {
                    XmlSchemaSet xssArchContent = new XmlSchemaSet();// 構造Schema架構快取
                    xssArchContent.Add("http://121.18.78.216", xsdFile);// 新增架構檔案,前面是名稱空間,沒有為空
                    XmlReaderSettings xrsArchContent = new XmlReaderSettings();// 定義公文模式的使用方式
                    xrsArchContent.ValidationType = ValidationType.Schema;
                    xrsArchContent.Schemas = xssArchContent;// 關聯驗證讀取器與架構集合
                    // 添加發生錯誤時的事件處理程式
                    xrsArchContent.ValidationEventHandler += new ValidationEventHandler(dealValidationError);
                    //構建可進行校驗的讀取器並構造驗證讀取器
                    XmlReader xrArchContent = null;
                    if (xml.EndsWith(Constants.XML_SUFFIX, StringComparison.CurrentCultureIgnoreCase))
                    {
                        xrArchContent = XmlReader.Create(xml, xrsArchContent);
                    }
                    else
                    {
                        xrArchContent = XmlReader.Create(new StringReader(xml), xrsArchContent);
                    }
                    // 迴圈檢測所有的文件節點
                    while (xrArchContent.Read())
                    {
                        if (xrArchContent.NodeType == XmlNodeType.Element
                            && msgCheck.IndexOf("#NODENAME#") != -1)
                        {
                            msgCheck = msgCheck.Replace("#NODENAME#", xrArchContent.Name);
                        }
                    }
                    xrArchContent.Close();
                }
            }
            catch (Exception ex)
            {
                msgCheck += ex.Message;
            }
            return msgCheck.Replace("#NODENAME#", String.Empty);
        }
        /// <summary>
        /// 錯誤處理程式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private static void dealValidationError(object sender, ValidationEventArgs args)
        {
            msgCheck += "#NODENAME#" + args.Message + Environment.NewLine;
        }
5、xml程式碼利用XmlDocument生成後總是一行,提供個格式化的方法

        /// <summary>
        /// 返回經過格式化處理的xml文件
        /// </summary>
        /// <param name="doc">xml文件物件</param>
        /// <returns></returns>
        public static string GetFormatXml(XmlDocument doc)
        {
            string result = null;
            if (doc != null)
            {
                try
                {
                    MemoryStream mstream = new MemoryStream(1024);
                    XmlTextWriter writer = new XmlTextWriter(mstream, null);
                    writer.Formatting = Formatting.Indented;
                    doc.WriteTo(writer);
                    writer.Flush();
                    writer.Close();

                    result = Encoding.UTF8.GetString(mstream.ToArray());
                    mstream.Close();
                }
                catch
                {
                    result = GetFormatXml(doc.OuterXml);
                }
            }
            return result;
        }
        /// <summary>
        /// 返回經過格式化處理的xml字串(增加換行)
        /// </summary>
        /// <param name="xml">xml字串</param>
        /// <returns></returns>
        public static string GetFormatXml(string xml)
        {
            if (String.IsNullOrEmpty(xml))
            {
                return null;
            }
            else
            {
                return xml.Replace(">\r\n", ">").Replace(">", ">\r\n");
            }
        }


試用請登入http://121.18.78.216/