c# - 对象到 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>
解决方案
尝试以下:
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;}
}
}
推荐阅读
- c# - 如何对 WPF 应用程序启用 DPI 感知并根据屏幕分辨率对其进行缩放
- shared-hosting - 共享虚拟主机的内容需要几分钟才能刷新
- c# - 需要c#在代码中填充一个类的多条记录
- javascript - ./ vs 路径和文件链接中的目录名
- javascript - 如何使 vuelidate alpha vuejs3 具有全局 $v 函数而不是在每个 vue 文件中声明?
- ruby-on-rails - 我无法使用普通 Rails + Turbolinks Shopify 应用程序
- list - NoSuchMethodError:null 上的无效成员:'length'
- firebase - Firestore 查询带有“hasOnly”的规则
- python - 使用进程从 C++ 程序获取数据到 Python 程序
- python - 使用 NLTK 预处理文本字符串