【问题标题】:Xml Serialization in C#C#中的Xml序列化
【发布时间】:2026-01-12 03:30:01
【问题描述】:

我正在尝试关注关于 XML 序列化的 microsoft tutorial,但我遇到了一些问题!!

这是 XML 文件,用作输入:

<?xml version="1.0" encoding="utf-8"?>
<Books xmlns:books="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
  <money:Book>
    <books:TITLE>A Book Title</books:TITLE>
    <money:PRICE books:currency="US Dollar">
      <money:price>9.95</money:price>
    </money:PRICE>
  </money:Book>
</Books>

这是绑定 XML 的类:

public class OrderedItem
{
        [XmlElement(Namespace = "http://www.cpandl.com")]
        public string ItemName;
        [XmlElement(Namespace = "http://www.cpandl.com")]
        public string Description;
        [XmlElement(Namespace = "http://www.cohowinery.com")]
        public decimal UnitPrice;
        [XmlElement(Namespace = "http://www.cpandl.com")]
        public int Quantity;
        [XmlElement(Namespace = "http://www.cohowinery.com")]
        public decimal LineTotal;
        // A custom method used to calculate price per item.
        public void Calculate()
        {
            LineTotal = UnitPrice * Quantity;
        }
    }

此函数将 XML 读入“OrderedItem”类:

Console.WriteLine("Reading with Stream");

// Create an instance of the XmlSerializer.
var serializer = new XmlSerializer(typeof(OrderedItem));

// Reading the XML document requires a FileStream.
Stream reader = new FileStream(filename, FileMode.Open);

// Declare an object variable of the type to be deserialized.
// Call the Deserialize method to restore the object's state.
var i = (OrderedItem)serializer.Deserialize(reader);

Console.SetOut(new StreamWriter("a_output.xml"));
serializer.Serialize(Console.Out, i);

这是读取和重写后的XML:

<?xml version="1.0" encoding="utf-8"?>
<OrderedItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ItemName xmlns="http://www.cpandl.com">Widget</ItemName>
  <Description xmlns="http://www.cpandl.com">Regular Widget</Description>
  <UnitPrice xmlns="http://www.cohowinery.com">2.3</UnitPrice>
  <Quantity xmlns="http://www.cpandl.com">10</Quantity>
  <LineTotal xmlns="http://www.cohowinery.com">23</LineTotal>
</OrderedItem>

如您所见,命名空间已扩展。我应该如何编写输出,以获得与命名空间标签相同的 XML,而不是 uri?

【问题讨论】:

    标签: .net xml serialization xml-deserialization


    【解决方案1】:

    您可能想看看用于序列化对象的重载方法:

    default serialization

    defining namespaces for serialization

    如上所述,您可以使用以下代码行定义XmlSerializerNamespaces

        // Create an XmlSerializerNamespaces object.
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    
        // Add two prefix-namespace pairs.
        ns.Add("inventory", "http://www.cpandl.com");
        ns.Add("money", "http://www.cohowinery.com");
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      为了将对象序列化为上面提供的格式,您必须在对象 (MSDN Documentation) 上实现 IXmlSerializable 接口。这个接口允许你实现一些方法,让你完全控制你的类的序列化结果(也可以将 xml 反序列化回你的对象)。

      这里也讨论过这个话题,查看这里了解更多信息:Proper way to implement IXmlSerializable

      【讨论】:

        【解决方案3】:

        查看XmlSerializerNameSpaces 类:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializernamespaces.aspx

        这个示例代码应该可以解决问题:

          XmlSerializer s = new XmlSerializer(typeof(OrderedItem));
          XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
          ns.Add("books", "http://www.cpandl.com");
          ns.Add("money", "http://www.cohowinery.com");    
          s.Serialize(new StreamWriter("a_output.xml"), i, ns);
        

        【讨论】:

          【解决方案4】:

          你需要添加一个XmlSerializerNamespaces类型的成员,用XmlNamespaceDeclarationsAttribute标记:

          public class OrderedItem
          {
            [XmlNamespaceDeclarations]
            public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
          
            ...
          }
          

          然后在序列化的时候加上命名空间声明:

          OrderedItem item = new OrderedItem();
          item.xmlns.Add("books", "http://www.cpandl.com");
          item.xmlns.Add("money", "http://www.cohowinery.com"); 
          XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem));
          ...
          

          【讨论】: