简体   繁体   中英

LINQ to XML: Don't Create XAttribute if value is DBNull.Value

I am querying a database using C# and creating a DataTable . From this DataTable I am using LINQ to XML to create an XML file.

My problem is that for null columns in the data table, when I call SetAttributeValue on an element, it creates a blank attribute. SetAttributeValue(name, value) doesn't add the attribute at all if value is null . Is there a way to mimic this behavior for DBNull.Value ? I don't want to check every single row and column to see if the value equals DBNull.Value .

Expected:

<Root>
    <Element1 E1="Test"/>
</Root>

Actual:

<Root>
    <Element1 E1="Test" E2=""/>
</Root>

Code for Element1:

DataTable testTable = new DataTable();
testTable.Columns.Add("E1");
testTable.Columns.Add("E2");

testTable.Rows.Add("Test", DBNull.Value);

XElement element = new XElement("Element1");

element.SetAttributeValue("E1", testTable.AsEnumerable().Select(item => item["E1"]));
element.SetAttributeValue("E2", testTable.AsEnumerable().Select(item => item["E2"]));

return element;

Write yourself an extension method:

public static class Extension
{
    public static void SetAttributeValueEx(this XElement source, XName name, object value)
    {
        if (value == DBNull.Value) value = null;
        source.SetAttributeValue(name, value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM