mohammad mobasher
mohammad mobasher

Reputation: 777

Get a value from XML?

I want to parse this XML and get cellphone number

<Result>
  <text_message>
    <id>4394</id>
    <message>2</message>
    <time>1373998420</time>
    <message_phone>
      <cellphone>09102805755</cellphone>
    </message_phone>
  </text_message>
</Result>

my code is:

int Num;
XDocument doc = XDocument.Parse(sms.InboxCheck(authsms, "1", "1", "0"));
doc.Save(Server.MapPath(".") + "\\xmlfolder\\xmlfile2.xml");
ds.ReadXml(Server.MapPath(".") + "\\xmlfolder\\xmlfile2.xml");
Num = Convert.ToInt32(ds.Tables["text_message"].Rows[0][3].ToString());
Label1.Text= Num.ToString();

value of this Rows[0][3] is 0

How can I fetch cellphone number?

Upvotes: 1

Views: 113

Answers (4)

sora0419
sora0419

Reputation: 2378

I would use XmlDocument instead.

XmlDocument doc = new XmlDocument();
doc.Load("myFile.xml");
XmlNode phone = doc.SelectSingleNode("/Result/text_message/message_phone/cellphone");
string number = phone.InnextText; 

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

How about continuing to leverage the XDocument class?

XDocument doc = XDocument.Load(sms.InboxCheck(authsms, "1", "1", "0"));
var cellphone = doc.Root.Element.Elements("message_phone").First().Element.Value

Upvotes: 5

do something like this

int num = int.parse(doc.Descendants.("cellphone").Single().Value);

or better yet

string num = doc.Descendants.("cellphone").Single().Value;

Upvotes: 3

Gustavo Azevedo
Gustavo Azevedo

Reputation: 113

Have you considered using Serialization?

You can map your xml to a Data Structure (Class) and read it or/and write to it via XmlSerializer or DataContractSerializer.

Upvotes: 0

Related Questions