Search code examples
c#xmllinqxelementxattribute

c# LINQ get Attribute value from XElement


I have the below XML in a data definitions file:

<PQTemplate documentID="CSTrlsEN" documentType="TransList" templateID="001" 
        templateType="Customer Copy" 
        templateName="C:\CPS\_templates\Mini-Statements\CSTrlsEN.doc">  
<field pos="5" name="YPTME" descr="Time"  />
<field pos="6" name="YPDTE" descr="Action Date"  />
<field pos="7" name="YPBRNO" descr="Branch Number"  />
<field pos="8" name="YPBNA" descr="Branch Name"  />
<field pos="9" name="YPTID" descr="Teller ID"  />
<field pos="10" name="YPISN" descr="Teller Sequence"  />
<field pos="11" name="YPREF" descr="Customer Reference"  />
<field pos="12" name="YPCUS" descr="Customer Name"  />
<field pos="13" name="YPEAN" descr="Account Number"  />
<field pos="14" name="YPATY" descr="Account Type"  />
<field pos="15" name="YPCUR" descr="Currency"  />
<field pos="16" name="YPBAL" descr="Available Balance"  />

I get that specific XElement using LINQ, extracting it from an XML file that contains several PQTemplate elements by using the below LINQ Expression:

var mapInfo = from nm in XElement.Elements("PQTemplate")
                where (string)nm.Attribute("documentID") == sRequests[0].Split('\t')[0] 
                select nm;    

Now I need to get the value of the attribute documentType so I tried the below LINQ Expression:

var repName = from d in mapInfo.Attributes("documentType")
                     select d.Value;

reportName = repName.ToString();

Unfortunately although I can see the value TransList is part of the reportName element, I have had no luck trying to retrieve it.

Here is an image showing it in VS 2013:

enter image description here

so how can I get the documentType attribute in the element?


Solution

  • That's because repName will return an IEnumerable<string> for all the mapInfo.

    IEnumerable<string> repName = from d in mapInfo.Attributes("documentType")
                         select d.Value;
    

    So either use a foreach loop if you suspect you may get more values or use First to get first attribute like this:-

    string reportName = mapInfo.First().Attribute("documentType").Value;