【问题标题】:Custom XML Serialization with x:使用 x 的自定义 XML 序列化:
【发布时间】:2021-10-27 16:44:29
【问题描述】:

我正在尝试使用 C# 中的自定义标记生成/序列化 XML 文件,即使我尝试了多种解决方案,我也无法提出有效的解决方案,我将不胜感激。该文件应如下所示:

<?xml version="1.0" encoding="utf-8"?>
  <x:Todo>
    <Id>1</Id>
    <x:UserId>27</UserId>
 </Todo>

问题是我不知道如何将 x: 添加到特定节点的标签中。

提前感谢您的所有贡献。 我

【问题讨论】:

    标签: c# .net xml file


    【解决方案1】:

    你需要定义命名空间并使用它,这里是一个例子(来自here):

    using System;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    
    public class Run
    {
        public static void Main()
        {
            Run test = new Run();
            test.SerializeObject("XmlNamespaces.xml");
        }
    
        public void SerializeObject(string filename)
        {
            XmlSerializer s = new XmlSerializer(typeof(Book));
            // Writing a file requires a TextWriter.
            TextWriter t = new StreamWriter(filename);
    
            /* Create an XmlSerializerNamespaces object and add two
            prefix-namespace pairs. */
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("x", "http://www.cpandl.com");
    
            // Create a Book instance.
            Book b = new Book();
            b.TITLE = "A Book Title";
            s.Serialize(t, b, ns);
            t.Close();
        }
    }
    
    [XmlType(Namespace = "http://www.cpandl.com")]
    public class Book
    {
        [XmlElement(Namespace = "http://www.cpandl.com")]
        public string TITLE;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-08
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2014-12-18
      • 2012-01-31
      • 1970-01-01
      相关资源
      最近更新 更多