大马资讯论坛 - 马来西亚中文资讯平台

 找回密码
 注册
搜索

删除XML空值节点,Regex和XDocument Descendants范例-教学

[复制链接]
发表于 2013-6-8 09:08:24 | 显示全部楼层 |阅读模式
删除XML空值节点,Regex和XDocument Descendants范例-教学

尤其是int、datetime,只要空值,转换就出错了,null就出来了。

有两个方法:
第一:
Regex删除法,网友都不建议用这个,有效的去除空值最好用第二。
  1. string sXml = Regex.Replace(sXmlValue, @"<([^>/][^>]*)></\1>", String.Empty);
复制代码
第二:用XDocument.Descendants去除空值
  1. var document = XDocument.Parse(Xml);
  2. document.Descendants()
  3.         .Where(e => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value))
  4.         .Remove();

  5. MessageBox.Show(document.ToString());
复制代码

手机版|大马资讯论坛  

GMT+8, 2024-4-16 22:23 , Processed in 0.049144 second(s), 13 queries , File On.

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表