反序列化的xml在C#中的空元素 [英] Deserialize Xml with empty elements in C#

查看:757
本文介绍了反序列化的xml在C#中的空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试反序列化从供应商一些XML snippits为对象。问题是,我得到的每empy元素标签的格式无效。我可以反序列化对象没有问题时所有的元素具有值。或空元素ommitted。



XML SNIPPIT:




<富>
< propOne大于1&下; / propOne>
&下; propTwo />
&下; /富>




C#类别:

  [Serialilbe()] 
公共类Foo
{
公共美孚( ){}
[XmlElementAttribute(ISNULLABLE =真)]
公众诠释? propOne {获取;设置;}
[XmlElementAttribute(ISNULLABLE =真)]
公众诠释? propTwo {获取;设置;}
}



有没有对I类可以设置作出调整的解析?



是有一个简单的方法,我可以申请XSL来删除这些元素?



我应该使用正则表达式来删除空元素脱颖而出desrializing?



一个更好的办法吗?


解决方案

要清理掉这些节点最统一的方式似乎是一个正则表达式过滤器添加到解串器。




 公共静态牛逼反序列化< T>(串XML){
XmlSerializer的XS =新的XmlSerializer(typeof运算(T));
串cleanXml = Regex.Replace(XML,@&下; [α-ZA-Z]。[^(大于;&下;)] + />中,
新MatchEvaluator(RemoveText) );
的MemoryStream MemoryStream的=新的MemoryStream((新UTF8Encoding())GetBytes会(cleanXml));
XmlTextWriter的XmlTextWriter的=新的XmlTextWriter(MemoryStream的,Encoding.UTF8);
回报率(T)xs.Deserialize(MemoryStream的);
}




 静态字符串RemoveText(赛米){返回;} 


Trying to deserialize some xml snippits from a vendor into objects. The problem is that I'm getting an invalid format on every empy element tag. I can deserialize the object no problem when all of the elements have values. Or the empty elements are ommitted.

Xml Snippit:

<foo>
<propOne>1</propOne>
<propTwo />
</foo>

C# Class:

[Serialilbe()]     
public class foo
{ 
   public foo(){}
   [XmlElementAttribute(IsNullable = true)]
   public int? propOne {get;set;} 
   [XmlElementAttribute(IsNullable = true)]
   public int? propTwo {get;set;}   
 }

Is there a setting on the class I can make to adjust the parsing?
or
Is there an easy way I can apply xsl to remove these elements?
or
Should I use regEx to remove the empty elements be fore desrializing?
or
an even better way?

解决方案

The most uniform way to clean out these nodes appears to be to add a RegEx filter to the deserializer.

    public static T Deserialize<T>(string xml){
        XmlSerializer xs = new XmlSerializer(typeof(T));
        string cleanXml = Regex.Replace(xml, @"<[a-zA-Z].[^(><.)]+/>",
                                        new MatchEvaluator(RemoveText));
        MemoryStream memoryStream = new MemoryStream((new UTF8Encoding()).GetBytes(cleanXml));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        return (T)xs.Deserialize(memoryStream);
    }

  static string RemoveText(Match m) { return "";}

这篇关于反序列化的xml在C#中的空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆