如何从XML中读取dictionary元素



我正在尝试根据该值获取相关的XML属性,但无法使其工作。

我试图实现的是基于我想要输出元素名称的返回值。

我哪里错了?

到目前为止,这是我的代码:

XML:

<addresses>
    <address name="house 1">No 1</ipaddress>
    <address name="house 2">Flat 3</ipaddress>
    <address name="house 3">Siccamore Drive</ipaddress>
</addresses>

C#:

string configPath = _AppPath + @"HouseAddresses.xml";
XDocument addressXdoc = XDocument.Load(configPath);
XElement addressXmlList = addressXdoc.Element("traplistener");
foreach (XNode node in addressXmlLst.Element("addresses").Descendants())
{
    PropertyList = ("string")node.Attribute("name");  
}

XNode类型可以看作是一个"基"。正如文档所述,它是represents the abstract concept of a node (element, comment, document type, processing instruction, or text node) in the XML tree。例如,在XML上下文中,向text添加Attribute属性实际上没有意义。因此,XNode类型不提供Attribute属性。然而,XElement类型确实如此。因此,将您的foreach循环更改为以下版本,应该可以做到这一点:

foreach (XElement element in addressXmlLst.Element("addresses").Descendants())
{
    PropertyList = ("string")element.Attribute("name");  
}

代码上的"随机"注释:由于XElement扩展了XNode,因此Descendants()返回的元素被正确转换;因此,您的问题似乎来自于XNode没有公开Attribute属性的事实,而事实上,它源于不必要的类型转换。

作为改进,我建议如下:

foreach (XElement element in addressXmlLst.Element("addresses").Descendants())
{
    //check if the attribute is really there
    //in order to prevent a "NullPointerException"
    if (element.Attribute("name") != null)
    {
        PropertyList = element.Attribute("name").Value;
    }
}

除了Andrei的答案,您还可以通过LINQ:直接将xml转换为字典

var dictionary = addressXmlLst.Element("addresses").Descendants()
      .ToDictionary(
        element => element.Attribute("name").Value, // the key
        element => element.Value // the value
      );              

最新更新