字段类型的XML到对象转换

时间:2017-10-19 06:44:17

标签: c# .net xml xml-parsing

我需要按照我的xml创建Object,这个对象将用作c#中web服务的输入。

如果我有这个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 =“注意” >

如果我将类型作为公共属性,它将作为xml中的标记出现,如名称,类别即将到来,但我想使用Field标记,它被称为属性。我可以在C#中使用什么作为Field标记的属性。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

试试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; }
    }
}