I am trying to build a dictionary using an XSD file which I get from WSDL definition using LINQ to XML.
The nodes which I am trying to parse look something like this
<xsd:element maxOccurs="1" minOccurs="0" name="active" type="xsd:boolean"/>
<xsd:element maxOccurs="1" minOccurs="0" name="activity_due" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="additional_assignee_list" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="approval" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="approval_history" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="approval_set" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="assigned_to" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="assignment_group" type="xsd:string"/>
The link to the XML file is: https://dl.dropboxusercontent.com/u/97162408/incident.xml
I am only worried about "getKeys".
Basically want to build a dictionary which will give me a key-value pair for "name" and "type" from the above sample node list.
I have got to a point where I can get to the Node list using the code
XNamespace ns = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
XDocument xd = XDocument.Load(url);
var result = (from elements in xd.Descendants(ns + "element") where elements.Attribute("name").Value.Equals("getKeys")
select elements.Descendants(ns + "sequence")
);
Now I wanted to build a dictionary in a single function call without writing another routine to parse through the result list using LINQ to XML. Any hints, code samples would be really helpful!!
ToDictionary
is your friend here. You can do it all in one statement:
var query = xd
.Descendants(ns + "element")
.Single(element => (string) element.Attribute("name") == "getKeys")
.Element(ns + "complexType")
.Element(ns + "sequence")
.Elements(ns + "element")
.ToDictionary(x => (string) x.Attribute("name"),
x => (string) x.Attribute("type"));
Basically the first three lines find the only element with a name of getKeys
, the next two three lines select the xsd:element
parts under it (you could just use Descendants(ns + "element")
if you wanted), and the final call transforms a sequence of elements into a Dictionary<string, string>
.
See more on this question at Stackoverflow