问题 LinQ to XML

  • Monday, March 04, 2013 4:35 AM
     
      Has Code

    Hi,

    I  want to get an node value which matches a specified attribute value.

    Below is my code...

    XElement xe = XElement.Load(strPath + "\\LogsTimeFormats.xml");
            Func<XElement, bool> whereClause;
            if (strFileName.Contains("*.*"))
            {
              whereClause = a => a.ToString().IndexOf(strFileName.Substring(0, a.ToString().Length - 4)) > -1;
            }
            var query = xe.Descendants("File").Where(whereClause).Select(a => a.Value);


    The above code does not work, throws exception on the line, 'whereclause =...."

    The 'strFileName' value that is passes is 'messages*.*'

    XMl file is

    <?xml version="1.0" encoding="utf-8" ?>
    <LogFiles>
      <File name="messages"><![CDATA[MMM  d HH:mm:ss]]></File>
      <File name="fusionserver*.*"><![CDATA[MMM d, yyyy h:mm:ss tt]]></File>
    </LogFiles>


    Can anyone help me o fix it? 

All Replies

  • Monday, March 04, 2013 8:14 AM
     
      Has Code

    Check if this solves your problem:

    if (strFileName.EndsWith("*.*"))
    {
        whereClause = a => a.Attribute("name").Value == strFileName.Substring(0, strFileName.ToString().Length - 3);
    }

    For some kinds of matches you can also use regular expressions.



    • Edited by Viorel_MVP Monday, March 04, 2013 8:16 AM
    •  
  • Tuesday, March 05, 2013 4:03 PM
     
      Has Code

    Hi Shanthi;

    I think this is what you may be looking for. You will need the else if the strFileName does not have a *.* so that you can build the function.

    Func<XElement, bool> whereClause = null;
    if (strFileName.Contains("*.*"))
      whereClause = a => a.Attribute("name").Value == strFileName.Substring(0, strFileName.IndexOf("*.*"));
    else
      whereClause = a => a.Attribute("name").Value == strFileName;
      
    var query = xe.Descendants("File").Where(whereClause).Select(a => a.Value);


      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

  • Tuesday, March 19, 2013 3:36 AM
     
     

       

    Have any of the post answered your question or are you still having issues?

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".