简体   繁体   中英

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?

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

do something like this

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

or better yet

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

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 .

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; 

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