项目中有时候要用XML作为数据源,因此需要定义XML文件和相应的类,最佳方法是首先定义XSD,然后自动生成实体类,最后生成XML和填充数据;读取XML数据源的时候,首先用XSD验证XML数据格式,然后自动读入实体类使用。
自动读取XML数据到实体类:
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->XmlSerializer xs =new XmlSerializer(typeof(myClassType)); using (FileStream fs =new FileStream(XmlFilePath, FileMode.Open)) { return (myClassType)xs.Deserialize(fs); }
如何由XML生成XSD?
- 可以用工具,如XMLSpy,首先打开XML, 然后DTD/Schema -> Generate DTD/Schema, 选择W3c Sehcma即可。
- 此方法不一定能生成确切满足需求的XSD,另需修改。
如何由XSD生成XML?
- 可以用其他工具,如XMLSpy,DTD/Schema -> Generate sample XML file...
- 可以由XSD生成类,然后写代码实例化这个类,最后序列化为XML
- 如何自动给类每个属性设置一个空值:(用反射的方法)
代码示例:
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->///<summary>/// Get all properties and set default value ///</summary>///<typeparam name="T">Type</typeparam>///<param name="item">Object</param>privatestaticvoid ReflctProperties<T>(T item) { PropertyInfo[] pty =typeof(T).GetProperties(); Type t = item.GetType(); if (pty !=null) { foreach (PropertyInfo info in pty) { if (!info.CanWrite) continue; if (info.PropertyType ==typeof(String)) { t.GetProperty(info.Name).SetValue(item, String.Empty, null); } if (info.PropertyType ==typeof(Boolean)) { t.GetProperty(info.Name).SetValue(item, true, null); } } } }
反射读取类的属性:
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->publicstaticobject GetProperty<T>(T item, string PropertyName) { PropertyInfo propertyInfo = item.GetType().GetProperty(PropertyName); if (propertyInfo !=null) { return propertyInfo.GetValue(item, null); } returnnull; }
如何序列化为XML?
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->///<summary>/// Serialize class instance to XML file ///</summary>///<typeparam name="T">type</typeparam>///<param name="XMLFileToCreate">XMLFileToCreate</param>///<param name="instance">class instance</param>publicvoid Serialize<T>(string XMLFileToCreate, T instance) { if (instance ==null) return; XmlSerializer xs =new XmlSerializer(typeof(T)); using (StreamWriter sw =new StreamWriter(XMLFileToCreate)) { xs.Serialize(sw, instance); } }
如何使用XSD来验证XML文件合法性:
- 使用XMLSpy,首先Assign XSD,然后验证 (其实就是设置XML里面引用的schema,注意schema可能引用其他的schema)
- 代码中验证:
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> Validate XML against XSD#region Validate XML against XSDpublicclass Validator { privatestring errMsg; /**////<summary>/// validation Error Msg ///</summary>publicstring validationErrMsg { get { return errMsg; } set { errMsg = value; } } /**////<summary>/// Validate XML against schema ///</summary>///<param name="XSD"></param>///<param name="XMLFile"></param>///<param name="LocationDefined"></param>///<returns></returns>publicbool 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; } /**////<summary>/// Display any warnings or errors. ///</summary>///<param name="sender"></param>///<param name="args"></param>publicvoid 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
<!-- google_ad_section_end -->
相关推荐
通过xsd产生C#实体类解析XML或生成XML,有疑问请私聊
将trang.jar和要解析的xml放在同一目录,在当前文件下执行如下命令,其中users.xsd为要生成的xsd文件名 java -jar trang.jar users.xml users.xsd 执行完上述命令后会在当前文件生成users.xsd,然后执行如下命令,...
JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到 XML实例...
2.xml文件是由元素和元素的内容以及属性组成的,一个xml文件中只能有一个根元素,标签和标签的内容加在一起叫作一个元素。xml是大小写 敏感的,只能以字母或下划线开头。 字符转义 < 代表 ", > 代表 ">" , &...
火龙果软件工程技术中心本页内容简介基础类扩展XSD处理XmlSerializer的内部原理通过CodeDom自定义映射技巧小结简介自动代码生成—无论是数据访问层、业务实体类还是用户界面—可以大大提高开发人员的生产效率。...
.wsdl 生成实体定义 Web 服务实现类配置 cxf jaxws 端点参考添加spring web配置创建 Web 应用程序 web.xml 描述符将 jetty maven 插件添加到启动实现 Web 服务客户端使用拦截器保护 Web 服务使用 WS-Policy 保护 Web...
利用反射实现ASP.NET控件和数据实体之间的双向绑定,并且在客户端自动验证输入的内容是否合法 asp.net报表解决方法 SQLDMO类的使用 SQL过程自动C#封装,支持从表到基本存储过程生成 使用SQLDMO控制 SQL Server 使用SQL...