由网友(微笑掩饰所有悲伤。)分享简介:我要寻找能有效去除空标签,从XML一个不错的办法。你有什么建议吗?正则表达式?的XDocument? XmlTextReader的? 例如,常量字符串原=@< XML版本=1.0编码=UTF-16,&GT?;<宠物><猫>汤姆< /猫><猪/><狗>小狗...
我要寻找能有效去除空标签,从XML一个不错的办法。你有什么建议吗?正则表达式?的XDocument? XmlTextReader的?
例如,
常量字符串原=
@< XML版本=1.0编码=UTF-16,&GT?;
<宠物>
<猫>汤姆< /猫>
<猪/>
<狗>小狗< /狗>
<蛇>< /蛇>
<大象>
< africanElephant>< / africanElephant>
< asianElephant> Biggy< / asianElephant>
< /大象>
< TIGER>
<虎伍兹>< /虎伍兹>
< americanTiger>< / americanTiger>
< / TIGER>
< / PET>中;
将变成:
常量字符串预计=
@< XML版本=1.0编码=UTF-16,&GT?;
<宠物>
<猫>汤姆< /猫>
<狗>小狗< /狗>
<大象>
< asianElephant> Biggy< / asianElephant>
< /大象>
< / PET>中;
解决方案
加载你原来成的XDocument
,并使用以下code给你想要的输出:
VAR文件= XDocument.Parse(原件);
document.Descendants()
。凡(E => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value))
卸下摆臂();
I am looking for a good approach that can remove empty tags from XML efficiently. What do you recommend? Regex? XDocument? XmlTextReader?
For example,
const string original =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<pet>
<cat>Tom</cat>
<pig />
<dog>Puppy</dog>
<snake></snake>
<elephant>
<africanElephant></africanElephant>
<asianElephant>Biggy</asianElephant>
</elephant>
<tiger>
<tigerWoods></tigerWoods>
<americanTiger></americanTiger>
</tiger>
</pet>";
Could become:
const string expected =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<pet>
<cat>Tom</cat>
<dog>Puppy</dog>
<elephant>
<asianElephant>Biggy</asianElephant>
</elephant>
</pet>";
解决方案
Loading your original into an XDocument
and using the following code gives your desired output:
var document = XDocument.Parse(original);
document.Descendants()
.Where(e => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value))
.Remove();
相关推荐
最新文章