简体   繁体   English

从元素获取属性列表

[英]get a list of attributes from an element

Still learning LINQ to XML and I'm having trouble parsing the data I want out. 仍在学习LINQ to XML,我在解析我想要的数据时遇到了麻烦。

The XML looks like this: XML如下所示:

<address address1="5750 Ramirez Canyon Road" city="Malibu" state="CA" otherstate=" " postalcode="90265" country="US">

I want to create a dictionary of all the attributes. 我想创建一个包含所有属性的字典。 I have been trying various things and I'm just confusing myself. 我一直在尝试各种各样的事情,只是让自己感到困惑。 I keep getting null reference exception errors etc. I've been trying stuff like this: 我不断收到null引用异常错误等。我一直在尝试如下操作:

var address = docCustomer
            .Element("address")
            .Attributes()
            .ToDictionary(....)

but obviously I'm doing something wrong because everything I try just bugs out. 但是很明显我做错了,因为我尝试的所有东西都出错了。

You haven't shown us the structure of your xml file. 您尚未向我们显示xml文件的结构。 docCustomer refers to your xml document, if you want to get child elements of your Root use: 如果要获取Root使用的子元素,则docCustomer引用您的xml文档:

 docCustomer
 .Root.Element("address")
 .Attributes()
 .ToDictionary(x => x.Name, x => (string)x);

If address is not the direct element of your root this wouldn't work.Use Descendants if that is the case: 如果address不是您的根目录的直接元素,那么将不起作用。在这种情况下,请使用Descendants

docCustomer
 .Descendants("address")
 .First()
 .Attributes()
 .ToDictionary(x => x.Name, x => (string)x);

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

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