我们如何使用c#从xml文件中获取数据

时间:2014-05-22 07:37:13

标签: c# xml

我创建了一个包含XML代码的字符串。从这个字符串我怎样才能获得值?

这是字符串

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <result>
        <country>India</country>
        <pincode>700001</pincode>
        <paymode>Prepaid</paymode>
        <service>Yes</service>
    </result>

我想要服务,付款,密码的价值。

1 个答案:

答案 0 :(得分:0)

例如,您可以使用XDocument

var doc = XDocument.Parse(
    @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
    <result>
        <country>India</country>
        <pincode>700001</pincode>
        <paymode>Prepaid</paymode>
        <service>Yes</service>
    </result>");


var country = doc.Root.Descendants().Single(d => d.Name == "country").Value;
var pincode = doc.Root.Descendants().Single(d => d.Name == "pincode").Value;
var paymode = doc.Root.Descendants().Single(d => d.Name == "paymode").Value;
var service = doc.Root.Descendants().Single(d => d.Name == "service").Value;