开发者

C# deserialize XML

I have problem with deserialize document to object using XmlSerializer class.

Code my function for deserialize:

   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 );
        } final开发者_开发技巧ly {
            stream.Close();
        }
        return message;
    }

And I have class:

    public class Test {
           public int a;
           public int b;
    }

And deserialize:

    string text = File.ReadAllText( "blue1.xml" );
    Test a = XmlInterpreter.xmlToObject<Test>( text );

Ok, when I read file like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <Test>
       <a>2</a>
       <b>5</b>
    </Test> 

everything is OK. But like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <Test>
        <a>2</a>
        <b></b>
    </Test> 

is wrong because

    <b></b> 

is empty and conversion into int is impossible.

How can I solve this? For example I want in this context that b will be not declared.

What when my class is:

    public class Test {

        public enum Pro {
             VALUE1,
             VALUE2
        }

        public Pro p1;
   }

And I want accept xmlDocument, where field p1 is empty.


I expect that first example is just some type because it has empty b as well. First of all not every XML can be deserialized to object. Especially empty elements are dangerous and should not be used. If you want to express that b is not defined then do not include it in XML file:

<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <a>2</a>
</Test> 

or make your b property nullable:

public class Test {
       public int a;
       public int? b;
}

and define XML as:

<?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> 

Generally if you want to use deserialization try to first use serialization to understand how must a valid XML look like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜