C#反序列化XML

C#反序列化XML,c#,xmlserializer,C#,Xmlserializer,我在使用XmlSerializer类将文档反序列化为对象时遇到问题 为我的函数编写反序列化代码: static public TYPE xmlToObject<TYPE>( string xmlDoc ) { MemoryStream stream = new MemoryStream(); byte[] xmlObject = ASCIIEncoding.ASCII.GetBytes( xmlDoc ); stream.Writ

我在使用
XmlSerializer
类将文档反序列化为对象时遇到问题

为我的函数编写反序列化代码:

   static public TYPE xmlToObject<TYPE>( string xmlDoc ) {
        MemoryStream stream = new MemoryStream();
        byte[] xmlObject = ASCIIEncoding.ASCII.GetBytes( xmlDoc );
        stream.Write( xmlObject, 0, xmlObject.Length );
        stream.Position = 0;

        TYPE message;

        XmlSerializer xmlSerializer = new XmlSerializer( typeof( TYPE ) );

        try {
            message = (TYPE)xmlSerializer.Deserialize( stream );
        } catch ( Exception e ) {
            message = default( TYPE );
        } finally {
            stream.Close();
        }
        return message;
    }
    string text = File.ReadAllText( "blue1.xml" );
    Test a = XmlInterpreter.xmlToObject<Test>( text );
并反序列化:

   static public TYPE xmlToObject<TYPE>( string xmlDoc ) {
        MemoryStream stream = new MemoryStream();
        byte[] xmlObject = ASCIIEncoding.ASCII.GetBytes( xmlDoc );
        stream.Write( xmlObject, 0, xmlObject.Length );
        stream.Position = 0;

        TYPE message;

        XmlSerializer xmlSerializer = new XmlSerializer( typeof( TYPE ) );

        try {
            message = (TYPE)xmlSerializer.Deserialize( stream );
        } catch ( Exception e ) {
            message = default( TYPE );
        } finally {
            stream.Close();
        }
        return message;
    }
    string text = File.ReadAllText( "blue1.xml" );
    Test a = XmlInterpreter.xmlToObject<Test>( text );

我想要接受
xmlDocument
,其中字段
p1
为空。

我希望第一个示例只是某种类型,因为它也有空的
b
。首先,并非所有XML都可以反序列化为对象。尤其是空元件是危险的,不应使用。如果要表示未定义
b
,请不要将其包含在XML文件中:

<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <a>2</a>
</Test> 
并将XML定义为:

<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <a>2</a>
    <b xsi:nil="true" />
</Test> 

2.

通常,如果要使用反序列化,请尝试首先使用序列化来理解有效XML的外观。

我希望第一个示例只是某种类型,因为它也有空的
b
。首先,并非所有XML都可以反序列化为对象。尤其是空元件是危险的,不应使用。如果要表示未定义
b
,请不要将其包含在XML文件中:

<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <a>2</a>
</Test> 
并将XML定义为:

<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <a>2</a>
    <b xsi:nil="true" />
</Test> 

2.
通常,如果要使用反序列化,请尝试首先使用序列化来了解有效XML的外观

public class Test {
       public int a;
       public int? b;
}
<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <a>2</a>
    <b xsi:nil="true" />
</Test>