Tom
Tom

Reputation: 8681

Traversing Specific XML Nodes and Modifying Values

I need to update both my mobile number and address. My program reads the XML string from the database. I am able to read the mobile number. How could I read the address in the same for loop. I also need to modify the values once read.

The XML string is below

<?xml version="1.0" encoding="utf-16"?>
<Test>
  <authentication>
    <company>Harissons</company>
    <username>[email protected]</username>
    <password>Pa55word67</password>
  </authentication>
  <sessions>
    <session RID="0cee7f47-59b4-4fb2-a8eb-bafba9dec8ee">
      <data>
        <Checksrequired>
          <BankStandard>Yes</BankStandard>
          <BankEnhanced>Yes</BankEnhanced>
          <CardLive>No</CardLive>
          <CardEnhanced>No</CardEnhanced>
          <IDEnhanced>Yes</IDEnhanced>
          <DeliveryFraud>No</DeliveryFraud>
          <EmailValidate>No</EmailValidate>
          <CreditScore>No</CreditScore>
          <Zodiac>No</Zodiac>
          <IPAddress>No</IPAddress>
        </Checksrequired>
        <Personalinformation>
          <IndividualDetails>
            <Title>Mr.</Title>
            <Firstname>test</Firstname>
            <Surname>test</Surname>
            <Dateofbirth>1996-02-01T00:00:00</Dateofbirth>
            <Emailaddress>[email protected]</Emailaddress>
          </IndividualDetails>
          <AddressDetails>
            <Buildingname></Buildingname>
            <Postcode>se93qS</Postcode>
            <Previouspostcode />
          </AddressDetails>
        </Personalinformation>
        <mobilenumber>9488488484</mobilenumber>
        <address>testaddress</address>
      </data>
    </session>
  </sessions>
  <application>LT-API-BEML</application>
</Test>

My code is written below

var testresults = ef.testtable.Where(x => x.test1 == 1).ToList();

testresults.ForEach(p =>
{
    XDocument testxml;
    using (var s = new System.IO.StringReader(p.TestM))
    {
        testxml = XDocument.Load(s);
        List<XElement> mobileNumbers = testxml.Descendants("mobilenumber").ToList();

        foreach (var mobilenumber in mobilenumbers)
        {
            int mobilenumber ;

            if (!int.TryParse(mobilenumber.Value, out mobilenumber ))
            {
                mobilenumber = 0;
            }
        }
    }
 });
 }
 ef.SaveChanges();

Upvotes: 0

Views: 42

Answers (1)

jdweng
jdweng

Reputation: 34421

Try this

                    var mobileNumbers = testxml.Descendants("data").Select(x => new {
                        mobilenumber = x.Element("mobilenumber").Value,
                        address = x.Element("address").Value,
                    }).ToList();

Upvotes: 1

Related Questions