无法使用有序元素反序列化带有 xml 注释的 XML

问题描述 投票:0回答:0

如果我反序列化包含注释元素的 XML 并将其反序列化为具有有序属性的类,我会得到异常:

XML 文件(4、25)有错误。 无法将“System.Xml.XmlElement”类型的对象转换为类型“System.Xml.XmlComment”。

这是 XML:

<?xml version="1.0" encoding="utf-8"?>
<ROOT>
    <!--Hello World-->
    <Field1>Hello1</Field1>
</ROOT>

当类中的字段标有属性“[XmlElement]”时,为什么 XmlSerializer 会尝试将

<Field1>
元素解析为 XmlComment?
(这仅在使用有序元素时发生!)。

C#类:

public class oFoo1
{
    [XmlAnyElement("Foo_Comment", Order = 0)]
    public XmlComment? FooComment { get; set; }

    [XmlElement(Order = 1)]
    public string? Field1;
            
    public oFoo1() {}
}

实例化对象和序列化的代码:

public static void Main()
{
    // Instantiate object
    var CFG = new oFoo1()
    {
        FooComment = new XmlDocument().CreateComment("Hello World"),
        Field1 = "Hello1",
    };

    // Serialize object
    Serialize_to_File<oFoo1>(Obj: CFG, Path: @"c:\temp\test.xml");

    // Deserialize object (will print exception)
    var Obj = Serialize_to_Object<oFoo1>(Path: @"c:\temp\test.xml");
}

public static void Serialize_to_File<T>(T Obj, string Path)
{
    XmlSerializerNamespaces NS = new XmlSerializerNamespaces();
    NS.Add(prefix:"", ns: "");
    XmlWriterSettings XWS = new XmlWriterSettings() {Indent = true, IndentChars = "\t"};

    using (XmlWriter XW = XmlWriter.Create(outputFileName: Path, settings: XWS))
    {
        XmlSerializer X = new XmlSerializer(typeof(T), root: new XmlRootAttribute("ROOT"));
        X.Serialize(xmlWriter: XW, o: Obj, namespaces: NS);
    }
}

public static object? Serialize_to_Object<T>(string Path)
{
    try
    {
        T? Obj;

        using (XmlReader XR = XmlReader.Create(inputUri: Path))
        {
            var XS = new XmlSerializer(typeof(T), new XmlRootAttribute("ROOT"));
            Obj = (T?)XS.Deserialize(XR);
        }

        return Obj;
    }
    catch (Exception Ex)
    {
        Console.WriteLine(
            Ex.Message + "\n" + 
            (Ex.InnerException ?? new Exception()).Message
            );
        return null;
    }
}
c# .net xml-deserialization xml-comments
© www.soinside.com 2019 - 2024. All rights reserved.