maephisto
maephisto

Reputation: 5182

XDocument get all nodes with attributes

I have the following XML document:

<parameters>
    <source value="mysource" />
    <name value="myname" />
    <id value="myid" />
</parameters>

I'm trying to parse this XML, using XDocument so that I would get a list (Dictionary) containing the node and it's value:

source => mysource,
name => myname,
id => myid

Any ideas on how I can do this?

Upvotes: 1

Views: 10089

Answers (6)

arcain
arcain

Reputation: 15290

I tried this out in LINQPad and it provides what you are looking for:

string xml = @"<parameters>
  <source value=""mysource"" />
  <name value=""myname"" />
  <id value=""myid"" />
</parameters>";

var doc = XDocument.Parse(xml);
IDictionary dict = doc.Element("parameters")
  .Elements()
  .ToDictionary(
    d => d.Name.LocalName, // avoids getting an IDictionary<XName,string>
    l => l.Attribute("value").Value);

Upvotes: 4

elder_george
elder_george

Reputation: 7889

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program{
    static void Main(){
        var doc = XDocument.Load("1.xml");
        var result = (from node in doc.Root.Elements()
                     select new{ Key = node.Name, Value = node.Attribute("value").Value})
                     .ToDictionary(p =>p.Key, p=>p.Value);
        foreach(var p in result) Console.WriteLine("{0}=>{1}", p.Key, p.Value);
    }
}

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

Something like this

XDocument doc = XDocument.Parse(xmlText);
IDictionary<string,string> dic = doc.Elements("parameters").ToDictionary(e => e.Name.LocalName, e => e.Value);

Hope this helps

Upvotes: 0

Deepesh
Deepesh

Reputation: 5614

You can use xmldocument/ xmtextreader object use these links these will help

http://msdn.microsoft.com/en-us/library/c445ae5y(v=vs.80).aspx

http://www.c-sharpcorner.com/uploadfile/mahesh/readwritexmltutmellli2111282005041517am/readwritexmltutmellli21.aspx

but i strongly suggest if possible use linq to xml that is far easy and manageable http://www.codeproject.com/KB/linq/LINQtoXML.aspx

Upvotes: 0

hemp
hemp

Reputation: 5683

XDocument x = XDocument.Parse(
            @"<parameters>
                <source value=""mysource"" />
                <name value=""myname"" />
                <id value=""myid"" />
            </parameters>");

var nodes = from elem in x.Element("parameters").Elements()
            select new { key = elem.Name.LocalName, value = elem.Attribute("value").Value };

var list = new Dictionary<string, string>();
foreach(var node in nodes)
{
    list.Add(node.key, node.value);
}

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134621

Provided you have a document with the content you show here, this should work:

XDocument doc = ...;
var dict = doc.Root
    .Elements()
    .ToDictionary(
        e => e.Name.ToString(),
        e => e.Attribute("value").Value);

Upvotes: 0

Related Questions