如何由XSD自动生成XML和实体类

项目中有时候要用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 -->
 
<!--正文内容结束--><!--关于内容的操作开始--><!--发表评论开始--><!-- 070328修改 ws begin -->
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值