views:

33

answers:

1

Here I had very similar xml structure, but now I have this:

<Fields>
    <Company>My Company</Company>
    <Address2>Villa at beach</Address2>
    <Email2>[email protected]</Email2>
    <Mobile>333-888</Mobile>
    <ContactMethod>Facebook</ContactMethod>
    ...etc...
</Fields>

And now I need the same output as on the given link: Company: My Company
Address2: Villa at beach
Email2: [email protected]

What would be the query for it?

Thanks,
Ile

+1  A: 

Assuming you want the results as a dictionary you could do this:

        string xml =
@"<Fields>  
  <Company>My Company</Company>  
  <Address2>Villa at beach</Address2>  
  <Email2>[email protected]</Email2>  
  <Mobile>333-888</Mobile>  
  <ContactMethod>Facebook</ContactMethod>  
</Fields>";

        XDocument doc = XDocument.Parse(xml);
        XElement fields = doc.Root;

        Dictionary<string, string> result = fields.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value);

        foreach (var i in result)
        {
            Console.WriteLine(i.Key + ": " + i.Value);
        }
Vitek Karas MSFT
Hi, thanks for answer, but this is not what I'm looking for. You hardcoded field names but I need it to dynamic determine field name and value.
ile
So the real question is: Do you want the result to be a dynamically generated type (real CLR type with the properties) or do you want it to be some kind of data structure, like Dictionary?Both are possible, but I would discourage you from using true CLR types as accessing those properties would require usage of reflection which is not very easy and very slow.So which one is it?
Vitek Karas MSFT
dictionary solution is the one I need. Thanks :)
ile