自动读取XML数据到实体类:
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
- 如何自动给类每个属性设置一个空值:(用反射的方法)
代码示例:
///
/// Get all properties and set default value
///
///
/// Object private static void ReflctProperties
{
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);
}
}
}
}
反射读取类的属性:
public static object GetProperty
{
PropertyInfo propertyInfo = item.GetType().GetProperty(PropertyName);
if (propertyInfo != null)
{
return propertyInfo.GetValue(item, null);
}
return null;
}
如何序列化为XML?
///
/// Serialize class instance to XML file
///
///
/// XMLFileToCreate/// class instance public void Serialize
{
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)
- 代码中验证:
Validate 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
沒有留言:
張貼留言