LinqToXml does not handle nillable elements as expected

后端 未结 3 1786
后悔当初
后悔当初 2020-12-20 00:32

According to W3C standards, if you have a nillable element with a nil value, you are supposed to format it like this:



        
3条回答
  •  感动是毒
    2020-12-20 01:17

    Hopefully, this is not the ideal answer, but I wrote a couple extension methods to at least make it a little easier to deal with nillable elements in LinqToXml.

    Extension Methods:

    public static class XElementExtensions
    {
        private static XName _nillableAttributeName = "{http://www.w3.org/2001/XMLSchema-instance}nil";
    
        public static void SetNillableElementValue(this XElement parentElement, XName elementName, object value)
        {
            parentElement.SetElementValue(elementName, value);
            parentElement.Element(elementName).MakeNillable();
        }
    
        public static XElement MakeNillable(this XElement element)
        {
            var hasNillableAttribute = element.Attribute(_nillableAttributeName) != null;
            if (string.IsNullOrEmpty(element.Value))
            {
                if (!hasNillableAttribute)
                    element.Add(new XAttribute(_nillableAttributeName, true));
            }
            else
            {
                if (hasNillableAttribute)
                    element.Attribute(_nillableAttributeName).Remove();
            }
            return element;
        }
    }
    

    Example Usage

    // "nil" attribute will be added
    element.Add(
        new XElement(NS + "myNillableElement", null)
        .MakeNillable();
    
    // no attribute will be added
    element.Add(
        new XElement(NS + "myNillableElement", "non-null string")
        .MakeNillable();
    
    // "nil" attribute will be added (if not already present)
    element.SetNillableElementValue(NS + "myNillableElement", null);
    
    // no attribute will be added (and will be removed if necessary)
    element.SetNillableElementValue(NS + "myNillableElement", "non-null string");
    

提交回复
热议问题