在序列化时需要制作XML标签(C#)

时间:2013-09-12 12:47:03

标签: c# xml serialization

我正在尝试将XML文件序列化为对象,在删除XML标记时,我期待一个例外,因为我的XML文件不再有效,但我仍然得到带有已删除标记的数据对象(属性) ) 一片空白。如何使这个特定的标签成为必需,所以当试图序列化它时,它会抛出一个异常,说标签xxx缺失=> XML文件无效 =>所以数据对象也是空的。

我的XSD

...
<xs:element name="Language" minOccurs="1" maxOccurs="1">
...

我的XML

<?xml version="1.0" encoding="iso-8859-1"?>
<root>
  <item>
    <sub1>1037</sub1>
    <Language>F</Language><!-- If I delete this tag, my XML file should be invalid -->
    <sub1>ZDC</sub1>
  </item>
 <root>

我的序列化工具

...
        /// <remarks/>
        public string Language
        {
            get
            {
                return this.languageField;
            }
            set
            {
                this.languageField = value;
            }
        }
...

1 个答案:

答案 0 :(得分:2)

我最终将XSD文件作为嵌入式资源添加到我的解决方案中并使用此方法:

public static void ValidateXmlFile<T>(string file, string xsdPath)
{
    var assembly = typeof(T).Assembly;
    var assName = assembly.GetName().Name;
    var xsdFullPath = String.Format("{0}.{1}", assName, xsdPath);
    var schema = assembly.GetManifestResourceStream(xsdFullPath);
    if (schema == null)
        throw new Exception(String.Format("{0} could not be validated, the XSD schema {1} not found", file, xsdFullPath));
    var xmlIsValid = true;
    var errorMsg = String.Empty;
    var schemaReader = XmlReader.Create(schema);
    var settings = new XmlReaderSettings();
    settings.Schemas.Add(null, schemaReader);
    settings.ValidationType = ValidationType.Schema;
    settings.ValidationEventHandler += (sender, args) =>
    {
        xmlIsValid = false;
        errorMsg = args.Message;
    };

    using (var stream = new FileStream(file, FileMode.Open))
    {
        var xr = XmlReader.Create(stream, settings);
        while (xr.Read()) { }
        if (!xmlIsValid) throw new Exception(String.Format("XML file {0} is not valid: {1}", file, errorMsg));
    }
}

发现错误时,会引发异常,并提供有关错误的详细信息。