清理具有属性“nil=true”的 Xml 元素- 创建 linq 版本?
我正在尝试清理文档中带有属性“nil=true”的 Xml 元素。 我想出了这个算法,但我不喜欢它的外观。
有人知道这个算法的 linq 版本吗?
/// <summary>
/// Cleans the Xml element with the attribut "nil=true".
/// </summary>
/// <param name="value">The value.</param>
public static void CleanNil(this XElement value)
{
List<XElement> toDelete = new List<XElement>();
foreach (var element in value.DescendantsAndSelf())
{
if (element != null)
{
bool blnDeleteIt = false;
foreach (var attribut in element.Attributes())
{
if (attribut.Name.LocalName == "nil" && attribut.Value == "true")
{
blnDeleteIt = true;
}
}
if (blnDeleteIt)
{
toDelete.Add(element);
}
}
}
while (toDelete.Count > 0)
{
toDelete[0].Remove();
toDelete.RemoveAt(0);
}
}
I'm trying to cleans the Xml element with the attribut "nil=true" inside a document.
I come up with this algo but I don't like how it's look.
Do anyone know a linq version of this algo?
/// <summary>
/// Cleans the Xml element with the attribut "nil=true".
/// </summary>
/// <param name="value">The value.</param>
public static void CleanNil(this XElement value)
{
List<XElement> toDelete = new List<XElement>();
foreach (var element in value.DescendantsAndSelf())
{
if (element != null)
{
bool blnDeleteIt = false;
foreach (var attribut in element.Attributes())
{
if (attribut.Name.LocalName == "nil" && attribut.Value == "true")
{
blnDeleteIt = true;
}
}
if (blnDeleteIt)
{
toDelete.Add(element);
}
}
}
while (toDelete.Count > 0)
{
toDelete[0].Remove();
toDelete.RemoveAt(0);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
nil
属性的命名空间是什么?将其放入 { } 内,如下所示:What's the namespace of the
nil
attribute? Put that inside { } like this:这应该有效..
This should work..
扩展方法:
示例用法:
输出:
如您所见,节点
和
按预期删除。唯一需要注意的是,您不能在
节点上调用此方法,因为无法删除根节点,并且您将收到以下运行时错误:The extension method:
Sample usage:
output:
as you can see, nodes
<a>
and<d>
where removed as expected. The only thing to note is that you cannot call this method on the<Root>
node because the root node cannot be removed, and you will get this run-time error:我改变了解决该问题的方法,并避免在可为空类型上创建 nil
我使用以下
http ://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.90%29.aspx
I change my way to solve that issue and avoid to create nil on my nullable type
I use the following
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.90%29.aspx