简体   繁体   中英

Having problem in C# getting value from an XML subnode

I am trying to loop through a subnode while looping through another node. The code I am using is (a lot of processing code not relevant to the question removed).

private void InsertLineItems(IEnumerable<XElement> BillingCode, int visitId)
{
    if (BillingCode != null)
    {
        using (var visitRepo = db.GetVisitRepository())
        {
            foreach (var item in BillingCode)
            {
                if (item.Element("Code").Attribute("value").Value.Length < 9)
                {
                    foreach (var icditem in item.Descendants("ICD10List"))
                    {
                        var icd10code = item.Element("ICD10List").Element("ICD10Code").Attribute("value");
                    }
                }
            }
        }
    }
)

To parse the following XML

<BillingCodes>
    <BillingCodeDTO>
        <Code value="73100"/>
        <Description value="X-ray left lower leg"/>
        <Quantity value="1"/>
        <ICD10List>
            <ICD10Code value="Y34.9"/>
            <ICD10Code value="Y34.99"/>
            <ICD10Code value="M79.9"/>
        </ICD10List>
    </BillingCodeDTO>
    <BillingCodeDTO>
        <Code value="74120"/>
        <Description value="X-ray left foot"/>
        <Quantity value="1"/>
        <ICD10List>
            <ICD10Code value="Z03.9"/>
        </ICD10List>
    </BillingCodeDTO>
</BillingCodes>

The problem I am getting is that while looping through the ICD10List it is only returning the first value. Where am I going wrong in getting it to loop through all the values? I did try using the ICD10Code as the loop (code below, just changed the foreach), that looped the correct number of times but returned the same value each time.

  foreach (var icditem in item.Descendants("ICD10List").Descendants("ICD10Code"))
    { var icd10code = item.Element("ICD10List").Element("ICD10Code").Attribute("value");}

a) You only have one variable which you re-assign all over again. In the end you want to use a list or something.

b) you should make use of the icditem variable instead of accessing a fixed element. A good IDE would indicate a warning about an unused variable.

foreach (var icditem in item.Descendants("ICD10List").Descendants("ICD10Code"))
{ 
    var icd10code = icditem .Attribute("value");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM