简体   繁体   English

C#用相应数据类型的默认值替换空XML节点

[英]C# replace null XML node with respective data type's default value

i have to iterate a loop on about 400 different XML files and every time i will be getting different xml file. 我必须迭代大约400个不同的XML文件循环,每次我将获得不同的XML文件。

I have about 11 nodes in the XML(all coming as String ) and i am parsing this XML and storing the XML Element's values using Entity Framework in the Database (in different data types like Decimal , int , string , double ) 我在XML中有大约11个节点(全部以String ),我正在解析这个XML并使用Entity Framework在数据库中存储XML Element的值(在Decimalintstringdouble等不同的数据类型中)

I do not know which xml node will come as null and i do not want to add a null check for each and every node.. 我不知道哪个xml节点将为null,我不想为每个节点添加空检查。

Is there a way to implement a common null check for the whole XML file in the loop so if any node comes as null, i can assign it to the default value of respective data type in its respective Entity.. Some thing like the code snippet shown below:- 有没有办法在循环中对整个XML文件实现公共空值检查,因此如果任何节点为null,我可以将其分配给各自实体中相应数据类型的默认值。有些事情如代码片段如下所示: -

foreach (XmlNode node in tableElements)
{
    dcSearchTerm searchTermEntity = new dcSearchTerm();
    //Reference keywords: creation & assignment
    int IDRef = 0, salesRef = 0, visitsRef = 0, saleItemsRef = 0;
    DateTime visitDateRef = new DateTime();
    decimal revenueRef = 0;

    int.TryParse(node["id"].InnerText, out IDRef);
    searchTermEntity.SearchTerm = node["Search_x0020_Term"].InnerText;
    searchTermEntity.ReferrerDomain = node["Referrer_x0020_Domain"].InnerText;

    if (node["Country"] == null)
    {
        searchTermEntity.Country = "";
    }
    else
    {
        searchTermEntity.Country = node["Country"].InnerText;
    }

    DateTime.TryParse(node["Visit_x0020_Date"].InnerText, out visitDateRef);
    searchTermEntity.VisitEntryPage = node["Visit_x0020_Entry_x0020_Page"].InnerText;
    int.TryParse(node["Sales"].InnerText, out salesRef);
    int.TryParse(node["Visits"].InnerText, out visitsRef);

    decimal.TryParse(node["Revenue"].InnerText, out revenueRef);
    int.TryParse(node["Sale_x0020_Items"].InnerText, out saleItemsRef);

    // assigning reference values to the entity
    searchTermEntity.ID = IDRef;
    searchTermEntity.VisitDate = visitDateRef;
    searchTermEntity.Sales = salesRef;
    searchTermEntity.Visits = visitsRef;
    searchTermEntity.Revenue = revenueRef;
    searchTermEntity.SaleItems = saleItemsRef;
    searches.Add(searchTermEntity);

    return searches;
}

PS:- This is my first question on SO, please feel free to ask more details Waiting for a flood of suggestions ! PS: - 这是我关于SO的第一个问题,请随时询问更多细节等待大量的建议! :) :)

OK, here is extension class that adds methods to Strings and XmlNodes: 好的,这是扩展类,它为Strings和XmlNodes添加方法:

public static class MyExtensions
{
    // obviously these ToType methods can be implemented with generics
    // to further reduce code duplication
    public static int ToInt32(this string value)
    {
        Int32 result = 0;

        if (!string.IsNullOrEmpty(value))
            Int32.TryParse(value, out result);

        return result;
    }
    public static decimal ToDecimal(this string value)
    {
        Decimal result = 0M;

        if (!string.IsNullOrEmpty(value))
            Decimal.TryParse(value, out result);

        return result;
    }

    public static int GetInt(this XmlNode node, string key)
    {
        var str = node.GetString(key);
        return str.ToInt32();
    }

    public static string GetString(this XmlNode node, string key)
    {
        if (node[key] == null || String.IsNullOrEmpty(node[key].InnerText))
            return null;
        else
            return node.InnerText;
    }

    // implement GetDateTime/GetDecimal as practice ;)
}

Now we can rewrite your code like: 现在我们可以重写你的代码,如:

foreach (XmlNode node in tableElements)
{
    // DECLARE VARIABLES WHEN YOU USE THEM
    // DO NOT DECLARE THEM ALL AT THE START OF YOUR METHOD
    // http://programmers.stackexchange.com/questions/56585/where-do-you-declare-variables-the-top-of-a-method-or-when-you-need-them

    dcSearchTerm searchTermEntity = new dcSearchTerm()
    {
        ID = node.GetInt("id"),
        SearchTerm = node.GetString("Search_x0020_Term"),
        ReferrerDomain = node.GetString("Referrer_x0020_Domain"),
        Country = node.GetString("Country"),
        VisitDate = node.GetDateTime("Visit_x0020_Date"),
        VisitEntryPage = node.GetString("Visit_x0020_Entry_x0020_Page"),
        Sales = node.GetInt("Sales"),
        Visits = node.GetInt("Visits"),
        Revenue = node.GetDecimal("Revenue"),
        SaleItems = node.GetDecimal("Sale_x0020_Items")
    };

    searches.Add(searchTermEntity);

    return searches;
}

Don't forget to implement GetDateTime and GetDecimal extensions- I've left those to you ;). 不要忘记实现GetDateTime和GetDecimal扩展 - 我已经把它们留给了你;)。

You can use a monad style extension method like below. 您可以使用如下所示的monad样式扩展方法。 The sample provided acts only on structs. 提供的样本仅作用于结构。 You can modify it to use for all types. 您可以修改它以用于所有类型。

public static class NullExtensions
{
    public delegate bool TryGetValue<T>(string input, out T value);

    public static T DefaultIfNull<T>(this string value, TryGetValue<T> evaluator, T defaultValue) where T : struct
    {
        T result;

        if (evaluator(value, out result))
            return result;

        return defaultValue;
    }

    public static T DefaultIfNull<T>(this string value, TryGetValue<T> evaluator) where T : struct
    {
        return value.DefaultIfNull(evaluator, default(T));
    }
}

Example: 例:

string s = null;
bool result = s.DefaultIfNull<bool>(bool.TryParse, true);
int r = s.DefaultIfNull<int>(int.TryParse);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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