Quantcast
Channel: XML, System.Xml, MSXML and XmlLite forum
Viewing all articles
Browse latest Browse all 935

Can Query remove need for loop ( get attribute if value matches)

$
0
0

I have already downsized my XML fragment to the Node I want.  The code works below (  there are 2 workable approached ) - but I thought I could use LINQ and lamda expression to query from the start - rather than load the dictionary and then clear it if the conditions are not met ( = an attributeName has a specific value ) - ideas ??? 

       public Dictionary<string, string> GetElementAttributesWithKeyByValueCondition(string XMLFragSource, string attribValue, string attribName)
        {  // get all the attributes from the element if attributeValue & attributeName match....

            var myKeyValReturn = new Dictionary<string, string>();
            bool found= false;
            try
            {
                XElement allData = XElement.Parse(XMLFragSource);
                if (allData != null)
                {
                    IEnumerable<XAttribute> telementAttrib = allData.Attributes();
                    foreach (XAttribute xattr in telementAttrib)
                    {
                        myKeyValReturn.Add(xattr.Name.ToString(), xattr.Value);  //&& xattr.Name=attribName)  what's this ? cannot use && ?
                        if (xattr.Name == attribName)
                        {
                            if (xattr.Value == attribValue)
                            { found = true;}
                        }
                    }
                    if (!found)
                    {
                        myKeyValReturn.Clear();
                    }

                      // alternate to bool flag
                      IEnumerable<KeyValuePair<string,string>> kvp=  myKeyValReturn.Where(a=>(a.Value==attribValue && a.Key==attribName));
                      if (kvp.Count()<1)
                      {
                          myKeyValReturn.Clear();  // did not find it.
                      }

                    //  how does this work ??
                    IEnumerable<XAttribute> tAttrib =
                    from a in allData.Attributes()
                    where  a.Value==attribValue
                    select a ;


                }

            }
            catch (Exception e)
            {
                string errorMessage = string.Format("Fn GetElementAttributesWithKeyByValueCondition failed {0},{1}", e.Message, XMLFragSource);

            }

            return myKeyValReturn;

        }

Thanks


andrew


Viewing all articles
Browse latest Browse all 935

Trending Articles