简体   繁体   中英

How do I Convert XmlNode to C# Objects?

I consume a third-party web service that uses SOAP XML. I construct my XML request and get XML back like this:

<GetCustomers xmlns="">
  <Header>
    <Version>1.0</Version>
    <Type>GetCustomers</Type>
    <GeneratedDate>07/11/2013 13:30</GeneratedDate>
  </Header>
  <ResultMessage>
    <Message>7 Customers found</Message>
    <Code>CustomerFound</Code>
    <Success>true</Success>
  </ResultMessage>
  <Customer>
    <CustomerName>CUSTOMER ABC</CustomerName>
    <CustomerID>33</CustomerID>
    <CustomerCode></CustomerCode>
  </Customer>

It returns it as an object type XmlNode and I want to convert this response into a ViewModel I have created as part of an MVC 4 app I am building. What is an approach that will work?

Convert the full XML into a string first:

string xml = response.OuterXml.ToString();

Then use XDocument:

XDocument xDoc = XDocument.Parse(xml);

Now use LINQ to XML to select each Customer element and create a list:

var obj = (from element in xDoc.Descendants("GetCustomers").Elements("Customer")
           select new {
              ID = element.Element("CustomerID").Value,
              Name element.Element("CustomerName").Value,
              Code = element.Element("CustomerCode").Value
           }).ToList();

I am sure there are many better ways to now convert this into my ViewModel data but this is how I did it:

foreach (var item in obj)
{
    RMCustomer customer = new RMCustomer();
    if (item.ID != null && item.ID.Length > 0)
    {
        customer.RMInternalUniqueID = Convert.ToInt32(item.ID);
    }

    if (item.Code != null && item.Code.Length > 0)
    {
        customer.CustomerRMExternalID = Convert.ToInt32(item.Code);
    }
    else
    {
        customer.CustomerRMExternalID = null;
    }
    if (item.Name != null && item.Name.Length > 0)
    {
        customer.CustomerName = item.Name;
    }
    if (customer != null)
    {
        roadMarqueCustomers.Add(customer);
    }
}

I should point out my ViewModel is simply:

public class RMCustomer
{
    public string CustomerName { get; set; }
    public int CustomerRMInternalUniqueID { get; set; }
    public Nullable<int> CustomerRMExternalID { get; set; }
}

Finally:

 return roadMarqueCustomers;

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