使用attribut“”清除Xml元素;nil=true”-创建linq版本

本文关键字:true 创建 linq nil 版本 attribut 清除 Xml 元素 使用 | 更新日期: 2023-09-27 18:24:05

我正在尝试清理文档中具有attribut"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);
        }
    }

使用attribut“”清除Xml元素;nil=true”-创建linq版本

nil属性的名称空间是什么?将其放入{}中,如下所示:

public static void CleanNil(this XElement value)
{
    value.Descendants().Where(x=> (bool?)x.Attribute("{http://www.w3.org/2001/XMLSchema-instance}nil") == true).Remove();
}

这应该有效。。

public static void CleanNil(this XElement value)
{
     var todelete = value.DescendantsAndSelf().Where(x => (bool?) x.Attribute("nil") == true);
     if(todelete.Any())
     {
        todelete.Remove();
     }
}

扩展方法:

public static class Extensions
{
    public static void CleanNil(this XElement value)
    {
        value.DescendantsAndSelf().Where(x => x.Attribute("nil") != null && x.Attribute("nil").Value == "true").Remove();
    }
}

示例用法:

File.WriteAllText("test.xml", @"
                <Root nil=""false"">
                    <a nil=""true""></a>
                    <b>2</b>
                    <c nil=""false"">
                        <d nil=""true""></d>
                        <e nil=""false"">4</e>
                    </c>
                </Root>");
var root = XElement.Load("test.xml");
root.CleanNil();
Console.WriteLine(root);

输出:

<Root nil="false">
  <b>2</b>
  <c nil="false">
    <e nil="false">4</e>
  </c>
</Root>

如您所见,节点<a><d>按预期移除。唯一需要注意的是,您不能在<Root>节点上调用此方法,因为根节点无法删除,并且您将得到以下运行时错误:

缺少父级。

我改变了解决该问题的方法,并避免在我的可为null的类型上创建nil我使用以下

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.90%29.aspx

    public class OptionalOrder
    {
        // This field should not be serialized 
        // if it is uninitialized.
        public string FirstOrder;
        // Use the XmlIgnoreAttribute to ignore the 
        // special field named "FirstOrderSpecified".
        [System.Xml.Serialization.XmlIgnoreAttribute]
        public bool FirstOrderSpecified;
    }