XML到字段类型的对象转换

问题描述:

我需要根据我的xml创建对象,该对象将用作c#中web服务的输入。XML到字段类型的对象转换

如果我有这样的XML,

<v1:Field type="Note"> 
    <v1:name>Buyer’s Name should be as per Passport/Trade License. For existing Emaar property owners, please provide details as per existing profile.</v1:name> 
    <v1:category>MESSAGE</v1:category> 
    <v1:mandatory>N</v1:mandatory> 
    <v1:alias>DESCLAIMER_FYI</v1:alias> 
    <v1:value>Buyer’s Name should be as per Passport/Trade License. For existing Emaar property owners, please provide details as per existing profile.</v1:value> 
</v1:Field> 

我可以让类此基础上, 例如

public class Field 
{ 
    public string name{ set; get; } 
    public string category { set; get; } 
    public string mandatory { set; get; } 
    public string alias { set; get; } 
    public string value { set; get; } 
} 

哪些属性将用于借此值 < V1:现场type =“Note”>

如果我将类型设置为公共属性,它将作为xml中的标签来使用,如名称,类别即将到来,但我希望使用Field标记(称为属性)。我可以在C#中使用哪些内容,这些内容将用作Field标记附带的属性。

public class SomeIntInfo 
{ 
    [XmlAttribute] 
    public int Value { get; set; } 
} 

尝试xml linq。我测试以下代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 

      XElement root = doc.Root; 
      XNamespace ns = root.GetNamespaceOfPrefix("v1"); 

      var results = root.Descendants(ns + "Field").Select(x => new Field() { 
       type = (string)x.Attribute("type"), 
       name = (string)x.Element(ns + "name"), 
       category = (string)x.Element(ns + "category"), 
       mandatory = (string)x.Element(ns + "mandatory"), 
       alias = (string)x.Element(ns + "alias"), 
       value = (string)x.Element(ns + "value"), 
      }).FirstOrDefault(); 
     } 
    } 
    public class Field 
    { 
     public string type { get; set; } 
     public string name { set; get; } 
     public string category { set; get; } 
     public string mandatory { set; get; } 
     public string alias { set; get; } 
     public string value { set; get; } 
    } 
}