项目需要和别的系统交互,要求只能用XML,⊙﹏⊙b汗的很 时间不够

先通过vs 带的工具xsd.exe 命令 生成对应xml的xsd ( 打开vs 的如命令提示 xsd InpXmlSt.xsd /t:lib /l:vb /c  /o:E:/Uc/操作其它进程测试3/InpOrdXmlDemo/InpXmlOpClasss)

1. 首先在VS2005中添加一个XSD文件。

2. 使用VS2005工具XSD.exe(SDK"v2.0"Bin"xsd.exe)自动生成实体类:

xsd /c /namespace:myCompany /language:CS temp1.xsd

也可以生成DataSet类型的类:

xsd /dataset /language:CS temp1.xsd

( 类文件和XSD之间可以相互转换,也就是说,你也可以先生成类,然后自动生成XSD)

 

    自动读取XML数据到实体类:

<Serializable()> _
Public Class S01
    Public Operation As Integer


    Public CaseID As String


    Public CreatedWhen As String


    Public lsthj As New List(Of DateTime)


End Class
<Serializable()> _
Public Class ResaultInfo
    Public ResultValue As Integer
    Public ResultInfo As String
End Class


Public Class SerializFunc
    Public Shared Function Serializ(Of T)(ByVal obj As T) As String
        If Not GetType(T).IsSerializable Then
            Throw New Exception(GetType(T).Name & "is not Serializ")
        End If
        Using memoryStream As New MemoryStream()
            Dim formatter As New Serialization.XmlSerializer(GetType(T))
            formatter.Serialize(memoryStream, obj)
            memoryStream.Seek(0, SeekOrigin.Begin)
            Dim reader As New System.IO.StreamReader(memoryStream, Encoding.UTF8)
            Dim xmlstring = reader.ReadToEnd()
            Return xmlstring
        End Using
    End Function
    Public Shared Function DeSerialize(Of T)(ByVal xmlstring As String) As T
        If Not GetType(T).IsSerializable Then
            Throw New Exception(GetType(T).Name & "is not Serializ")
        End If
        Dim obj As T
        Dim encoding = Text.Encoding.UTF8
        Dim constructedBytes As Byte() = encoding.GetBytes(xmlstring)
        Using fs As New MemoryStream(constructedBytes)
            Dim formatter As New Serialization.XmlSerializer(GetType(T))
            obj = DirectCast(formatter.Deserialize(fs), T)
        End Using
        Return obj
    End Function


    Public Shared Function SoapSerialize(Of T)(ByVal obj As T) As String
        If Not GetType(T).IsSerializable Then
            Throw New Exception(GetType(T).Name & "is not Serializ")
        End If
        Using memoryStream As New MemoryStream()
            Dim formatter As New System.Runtime.Serialization.Formatters.Soap.SoapFormatter()
            formatter.Serialize(memoryStream, obj)
            memoryStream.Seek(0, SeekOrigin.Begin)
            Dim reader As New System.IO.StreamReader(memoryStream, Encoding.UTF8)
            Dim xmlstring = reader.ReadToEnd()
            Return xmlstring
        End Using
    End Function
    Public Shared Function SoapDeSerialize(Of T)(ByVal xmlstring As String) As T
        If Not GetType(T).IsSerializable Then
            Throw New Exception(GetType(T).Name & "is not Serializ")
        End If
        Dim obj As T
        Dim encoding = Text.Encoding.UTF8
        Dim constructedBytes As Byte() = encoding.GetBytes(xmlstring)
        Using fs As New MemoryStream(constructedBytes)
            Dim formatter As New System.Runtime.Serialization.Formatters.Soap.SoapFormatter()
            obj = DirectCast(formatter.Deserialize(fs), T)
        End Using
        Return obj
    End Function
End Class

4. 如何使用XSD来验证XML文件合法性:
   - 使用XMLSpy,首先Assign XSD,然后验证 (其实就是设置XML里面引用的schema,注意schema可能引用其他的schema)
   - 代码中验证:

   Validate XML against XSDValidate XML against XSD#region Validate XML against XSD

public class Validator
{
private string errMsg;

/**//**//**////


/// validation Error Msg
///
public string validationErrMsg
{
get { return errMsg; }
set { errMsg = value; }
        }


/**//**//**////
/// Validate XML against schema
///
///
///
///
///
public bool Validate(string XSD, string XMLFile, bool LocationDefined)
{
bool isValid = true;

try
{
                Stream schemaFile = null;

                XmlReaderSettings settings = new XmlReaderSettings();
                ValidationEventHandler SchemaValidationEventHandler = new ValidationEventHandler(ValidationCallBack);

                settings.ValidationType = ValidationType.Schema;
                settings.ValidationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.ValidationEventHandler += SchemaValidationEventHandler;

if (LocationDefined == true)
{
                    settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
                    settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
                }
else
{
                    schemaFile = new FileStream(XSD, FileMode.Open);

                    XmlSchema tmsSchema = XmlSchema.Read(schemaFile, SchemaValidationEventHandler);

                    settings.Schemas.Add(tmsSchema);
                }

using (XmlReader reader = XmlReader.Create(XMLFile, settings))
{
string test;

while (reader.Read() && isValid == true)
{
                        test = reader.Name;
                    }
                };

if (schemaFile != null)
{
                    schemaFile.Close();
                }
            }
catch (Exception e)
{
                validationErrMsg += "Exception occured when validating. " + e.Message;

                isValid = false;
            }

return isValid;
        }

/**//**//**////
/// Display any warnings or errors.
///
///
///
public void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
                validationErrMsg += "Matching schema not found. No validation occurred." + args.Message;
                validationErrMsg = args.Message;
            }
else
{
                validationErrMsg += "/nValidation error: " + args.Message;

                validationErrMsg = args.Message;
            }
        }
    }
#endregion

posted on 2009-09-17 03:00  宋元  阅读(194)  评论(0编辑  收藏  举报