【问题标题】:Failed to read attributes from XML file无法从 XML 文件中读取属性
【发布时间】:2014-11-29 15:52:53
【问题描述】:

我已经尝试了很多尝试,也做了很多阅读和研究。这个最终代码最终读取了我的 XML 文件,并在我的 XML 文件中获得了正确的行数。但是,我在字典类型变量中得到的是 Null 值

这是我的代码:

public void ParkingStatus()
{
    _Default defaultPage = new _Default();

    //baca dari XML file
    XDocument xmlDocReader = XDocument.Load(@".\carpark.xml");

    var tempDict = xmlDocReader.Root.Elements("Lot")
        .ToDictionary(c => c.Elements("name"), c => c.Elements("timeOut"));

    foreach (var iterate in tempDict)
    {
        bool statusParking;
        if (iterate.Value.ToString() == "")
            statusParking = true;
        else
            statusParking = false;

        defaultPage.ParkingStatus.Add(iterate.Key.ToString(), statusParking);
    }
}      

我的 XML 文件如下:(carpark.xml)

<?xml version="1.0" encoding="UTF-8"?>

<Lot>
     <Lot name="W101" timeIn="2014-11-23 13:22" timeOut="" />
     <Lot name="W102" timeIn="" timeOut="2014-11-23 13:35" />
     <Lot name="W103" timeIn="" timeOut="2014-11-23 11:35" />
     <Lot name="W104" timeIn="2014-11-23 13:35" timeOut="" />
     <Lot name="W105" timeIn="2014-11-23 08:00" timeOut="" />
     <Lot name="W106" timeIn="2014-11-23 07:56" timeOut="" />
     <Lot name="W107" timeIn="" timeOut="2014-11-23 13:15" />
     <Lot name="W108" timeIn="2014-11-23 07:35" timeOut="" />
     <Lot name="W109" timeIn="" timeOut="2014-11-23 12:55" />
     <Lot name="W110" timeIn="2014-11-23 09:00" timeOut="" />
     <Lot name="W111" timeIn="" timeOut="2014-11-23 12:45" />
     <Lot name="W112" timeIn="" timeOut="2014-11-23 13:01" />
</Lot>

我做错了什么?

【问题讨论】:

    标签: c# xml linq dictionary


    【解决方案1】:

    Lot 是一个元素,但 nametimeIntimeout 是属性。

    <Lot name="W102" timeIn="" timeOut="2014-11-23 13:35" />
    

    因此,您应该在元素上使用Attributes 方法。

     var tempDict = xmlDocReader.Root.Elements("Lot")
            .ToDictionary(c => c.Attributes("name").FirstOrDefault(), 
                          c => c.Attributes("timeOut").FirstOrDefault());
    

    【讨论】:

    • 在调试添加到字典的键值时遇到此行defaultPage.ParkingStatus.Add(iterate.Key.ToString(), statusParking); 的另一个问题是“System.Xml.Linq.XElement+d_0”,它应该是“W101” 、“W102”等。在 tempDict 中,键值是正确的。因此我得到相同的重复键插入错误。
    【解决方案2】:

    不需要临时字典:

    foreach (var el in xmlDocReader.Root.Elements("Lot"))
    {
        string name = (string)el.Attribute("name");
        string timeOut = (string)el.Attribute("timeOut");
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2018-12-23
      • 1970-01-01
      相关资源
      最近更新 更多