将此XML解析为对象

时间:2014-11-18 20:47:13

标签: c# asp.net xml vb.net parsing

出于某种原因,对于那些对xml和对象了解不多的用户来说,这被广泛认可。这绝对不是一个广泛的问题。这是XML,并使用限定答案转换为对象。

我有以下XML,我不知道如何将其解析为对象。我不熟悉这种类型的xml。我的第一步是什么?我想把它解析成一个对象。

<?xml version="1.0" encoding="UTF-8" ?> 
<DATA_PROVIDERS UID="Providers|REP" FORCE_REFRESH="FALSE" DATA_PROVIDER="" FORMATTED="FALSE" REFRESH="TRUE">
<DATA_PROVIDER NAME="Prov" SOURCE="Provider" DATE="11/18/2014" DURATION="9s" REFRESH="TRUE" CUBE="1">
  <COLUMN INDEX="0" ID="119" TYPE="String" FORMAT="">Prov ID</COLUMN> 
  <COLUMN INDEX="1" ID="118" TYPE="String" FORMAT="">Prov Name</COLUMN> 
  <COLUMN INDEX="2" ID="113" TYPE="String" FORMAT="">Address Info</COLUMN> 
  <COLUMN INDEX="3" ID="110" TYPE="String" FORMAT="">Enroll Status Code</COLUMN> 
  <COLUMN INDEX="4" ID="119" TYPE="String" FORMAT="">Phone</COLUMN> 
  <COLUMN INDEX="5" ID="110" TYPE="String" FORMAT="">Fax</COLUMN> 
  <COLUMN INDEX="6" ID="109" TYPE="String" FORMAT="">Provider Status</COLUMN> 
  <COLUMN INDEX="7" ID="150" TYPE="Date" FORMAT="m/d/yyyy h:mm:ss am/pm">Provider Start Date</COLUMN> 
<ROW>
  <CELL INDEX="0">004042111</CELL> 
  <CELL INDEX="1">CONTOSO West INC</CELL> 
  <CELL INDEX="2">1234 Random Rd. SOMECITY, ZZ 12345 9876</CELL> 
  <CELL INDEX="3">F</CELL> 
  <CELL INDEX="4">5555551234123</CELL> 
  <CELL INDEX="5">5555551234</CELL> 
  <CELL INDEX="6">F - Agency Action</CELL> 
  <CELL INDEX="7">5/31/2011 12:00:00 AM</CELL> 
  </ROW>
<ROW>
  <CELL INDEX="0">004011117</CELL> 
  <CELL INDEX="1">CONTOSO North INC</CELL> 
  <CELL INDEX="2">4321 Random Rd. SOMECITY, ZZ 12345 9876</CELL> 
  <CELL INDEX="3">F</CELL> 
  <CELL INDEX="4">5555551234123</CELL> 
  <CELL INDEX="5">5555551234</CELL> 
  <CELL INDEX="6">F - Agency Action</CELL> 
  <CELL INDEX="7">5/31/2011 12:00:00 AM</CELL> 
  </ROW>
 </DATA_PROVIDER>
</DATA_PROVIDERS>

1 个答案:

答案 0 :(得分:7)

如果您使用的是Visual Studio 2012(或更高版本)并且您的目标是.NET 4.5(或更高版本),那么Visual Studio可以为您创建一个与XML匹配的类:

  • 将XML复制到剪贴板
  • 从Visual Studio中:编辑 - &gt;选择性粘贴 - &gt;将XML粘贴为类

然后,您需要将数据从XML序列化到新创建的类中以创建新对象:

var myObject = LoadFromXmlString<DATA_PROVIDERS>(xmlData);

public static T LoadFromXmlString<T>(string xml)
{
  T retval = default(T);
  try
  {
    XmlSerializer s = new XmlSerializer(typeof(T));
    MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(xml));
    retval = (T)s.Deserialize(ms);
    ms.Close(); 
  }
  catch (Exception ex)
  {
    ex.Data.Add("Xml String", xml);
    throw new Exception("Error loading from XML string.  See data.", ex);
  }
  return retval;

}