首页 > 解决方案 > 对象到 xml 并在不同的字段中添加不同的前缀和命名空间

问题描述

public class Item
        { 
          public string name {get;set;}
          public string code {get;set;}
        }

Item item=new Item{name="bd",code="001"}

我想将项目对象设置为 xml,如下例所示:

<Item>
    <p1:name url="https://t1.com"> bd</name>
    <p2:code url="https://t2.com">0001</code>
</Item>

标签: c#xml.net-corexml-serializationxmlserializer

解决方案


尝试以下:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            Item item = new Item()
            {
                name = new URL() { url = "https://t1.com", value = "bd" },
                code = new URL() { url = "https://t2.com", value = "0001" }
            };

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);

            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add("p1", "MyURL1");
            namespaces.Add("p2", "MyURL2");

            XmlSerializer serializer = new XmlSerializer(typeof(Item));
            serializer.Serialize(writer, item, namespaces);
        }
    }
    public class Item
    {
        [XmlElement(Namespace = "MyURL1")]
        public URL name { get; set; }
        [XmlElement(Namespace = "MyURL2")]
        public URL code { get; set; }
    }
    public class URL
    {
        [XmlAttribute()]
        public string url { get; set;}
        [XmlText]
        public string value { get; set;}
    }
}

推荐阅读