解析c#中的Web服务xml响应以获取变量中的特定节点值

时间:2015-08-04 07:05:18

标签: c# xml web-services xml-parsing

<NewDataSet>
  <Table>
    <Id>1         </Id>
    <ProductName>Hp Laptop</ProductName>
    <SerialNumber>abc111    </SerialNumber>
    <Status>Delivered           </Status>
    <CustomerName>Shatakshi</CustomerName>
  </Table>
</NewDataSet>

任何人都可以帮助我如何从我的网络服务响应中获取节点vaue

wordpress

我要做的是在相应的变量中获取id,productname,序列号,状态,cusomername值 plaese帮我理解我怎么能做到这一点。

1 个答案:

答案 0 :(得分:1)

将Linq用于XML。请注意,我没有网络服务 InventoryWebservice ,所以我只是手动创建一个xml文档。

using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        // create an XML document manually
        var doc = XDocument.Load(new StringReader(@"<NewDataSet>
  <Table>
    <Id>1         </Id>
    <ProductName>Hp Laptop</ProductName>
    <SerialNumber>abc111    </SerialNumber>
    <Status>Delivered           </Status>
    <CustomerName>Shatakshi</CustomerName>
  </Table>
</NewDataSet>"));

        // query the XML document
        var product = doc
            .Descendants("Table")
            .Select(x => new {
                        Id = x.Element("Id").Value,
                        ProductName = x.Element("ProductName").Value,
                        SerialNumber = x.Element("SerialNumber").Value,
                        Status = x.Element("Status").Value,
                        CustomerName = x.Element("CustomerName").Value
                        })
            .FirstOrDefault();

        // print the result
        if (product != null)
        {
            Console.WriteLine("Id = {0}", product.Id);
            Console.WriteLine("Product Name = {0}", product.ProductName);
            Console.WriteLine("Serial Number = {0}", product.SerialNumber);
            Console.WriteLine("Status = {0}", product.Status);
            Console.WriteLine("Customer Name = {0}", product.CustomerName);
        }

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}