从XML获取值?

时间:2013-07-17 14:22:23

标签: c# .net xml linq

我想解析这个XML并获得手机号码

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

我的代码是:

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();

Rows[0][3]的值为0

我如何获取手机号码?

4 个答案:

答案 0 :(得分:5)

如何继续利用XDocument课程?

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

答案 1 :(得分:3)

做这样的事情

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

或更好

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

答案 2 :(得分:0)

您是否考虑过使用序列化?

您可以将xml映射到数据结构(类)并将其读取或/并通过XmlSerializerDataContractSerializer写入。

答案 3 :(得分:0)

我会改用XmlDocument

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