LINQ to XML query help needed

本秂侑毒 提交于 2019-12-25 01:43:10

问题


I have the following XML structure...

<Fields>
    <Field>
        <Company>My Company</Company>
    </Field>
    <Field>
        <Address2>Villa at beach</Address2>
    </Field>
    <Field>
        <Email2>email2@mail.com</Email2>
    </Field>
    <Field>
        <Mobile>333-888</Mobile>
    </Field>
    <Field>
        <ContactMethod>Facebook</ContactMethod>
    </Field>
</Fields>

I would like to know how to get the element's name using LINQ? Something like this:

var fields = (from field in contact.XmlFields.Descendants("Field")
                   select new ContactXmlView {Field = ...,Value = ...});

I would like the output to be something like this:

Company: My Company
Address2: Villa at beach...

回答1:


Assuming that you have only one descendant for each "Field" node :

var fields = (from field in contact.XmlFields.Descendants("Field")
                          select new ContactXmlView
                          {
                              Field = field.Descendants().First().Name,
                              Value = field.Descendants().First().Value
                          });


来源:https://stackoverflow.com/questions/2738061/linq-to-xml-query-help-needed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!