简体   繁体   English

基于XML数据创建动态linq-XML

[英]Create dynamic linq-XML based on XML data

Goal: 目标:
To apply the XML data to the List _a 要将XML数据应用于List _a

Problem: 问题:
When making transaction of Jessica black I retrieve the error message "{"Object reference not set to an instance of an object."}" at the source code "_ab.age = li.Element("age").Value;" 当使Jessica交易变黑时,我在源代码"_ab.age = li.Element("age").Value;"检索到错误消息” {“对象引用未设置为对象的实例。”}“ "_ab.age = li.Element("age").Value;" because there is no data of Jessicas age in the xml. 因为xml中没有Jessicas年龄的数据。 Same problem can be for Jim West's sex. 吉姆·韦斯特(Jim West)的性生活也可能遇到同样的问题。

What should I do? 我该怎么办? I started getting crazy! 我开始疯了!

在此处输入图片说明


C # below C#以下

public class Program
{
private static List<user> _a = new List<user>();
private static user _ab = new user();


static void Main(string[] args)
{
    XDocument xml = XDocument.Load("xml file....");

    xml.Root.Descendants("user").ToList().ForEach(li =>
    {
        _ab = new user();
        _ab.firstname = li.Element("firstname").Value;
        _ab.lastname = li.Element("lastname").Value;
        _ab.age = li.Element("age").Value;
        _ab.sex = li.Element("sex").Value;
        _a.Add(_ab);
    }
}
}

public class user
{
    public String firstname;
    public String lastname;
    public String age;
    public String sex;
}   

XML code below 下面的XML代码

<users>
    <user>
        <firstname>sara</firstname>
        <lastname>brown</lastname>
        <age>20</age>
        <sex>female</sex>
    </user>
    <user>
        <firstname>Jessica</firstname>
        <lastname>black</lastname>
        <sex>Female</sex>
    </user>
    <user>
        <firstname>Jim</firstname>
        <lastname>west</lastname>
        <age>26</age>
    </user>
    <user>
        <firstname>robert</firstname>
        <lastname>lake</lastname>
        <age>41</age>
        <sex>male</sex>
    </user>
    <user>
        <firstname>Britany</firstname>
        <lastname>McLove</lastname>
        <age>21</age>
    </user>
</users>    

Use conversation operator: 使用对话运算符:

_ab.age = (string)li.Element("age");

and so on... 等等...

If element age doesn't exist, (string)li.Element("age") will return null and won't throw any exception. 如果元素age不存在,则(string)li.Element("age")将返回null且不会引发任何异常。

Just test if the element is not null before getting it's Value : 只是测试,如果元素得到它之前不为空Value

    xml.Root.Descendants("user").ToList().ForEach(li =>
    {
        _ab = new user();
        if (li.Element("firstname") != null) _ab.firstname = li.Element("firstname").Value;
        if (li.Element("lastname") != null) _ab.lastname = li.Element("lastname").Value;
        if (li.Element("age") != null) _ab.age = li.Element("age").Value;
        if (li.Element("sex") != null) _ab.sex = li.Element("sex").Value;
        _a.Add(_ab);
    }

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

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