我怎样才能正确序列化

问题描述 投票:0回答:2

如果我有一个类MovieClass

[XmlRoot("MovieClass")]
public class Movie
{
   [XmlElement("Novie")]
   public string Title;

   [XmlElement("Rating")]
   public int rating; 
}

如何在我的“Movie”元素中使用属性“x:uid”,以便在使用XmlSerializer XmlSerializer s = new XmlSerializer(typeof(MovieClass))时输出如下:

<?xml version="1.0" encoding="utf-16"?>
<MovieClass>
   <Movie x:uid="123">Armagedon</Movie>
</MovieClass>

而不是这样

<?xml version="1.0" encoding="utf-16"?>
<MovieClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Movie x:uid="123" Title="Armagedon"/>
</MovieClass>

注意:如果可能的话,我希望删除xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

c# xml-serialization
2个回答
2
投票

我在你的原帖中回答了这个问题,但是我认为这个措辞更好,所以我也会在这里发布,如果它被重复关闭,你可以修改原来的帖子来反映这个问题。

如果Title不是自定义类型或显式实现序列化方法,我认为这是不可能的。

你可以这样做一个自定义类..

class MovieTitle
{
    [XmlText]
    public string Title { get; set; }
    [XmlAttribute(Namespace="http://www.myxmlnamespace.com")]
    public string uid { get; set; }
    public override ToString() { return Title; }
}

[XmlRoot("MovieClass")]
public class Movie
{
   [XmlElement("Movie")]
   public MovieTitle Title;
}

这将产生:

<MovieClass xmlns:x="http://www.myxmlnamespace.com">
  <Movie x:uid="movie_001">Armagedon</Movie>
</MovieClass>

虽然序列化程序将补偿未知的命名空间,但结果可能是您不希望的。

您可以通过声明命名空间并将对象提供给序列化程序来避免这种奇怪的行为。

  XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
  ns.Add("x", "http://www.myxmlnamespace.com");

0
投票

如果没有将x声明为名称空间前缀,则它不是有效的XML。 Quintin的回复告诉您如何获得有效的XML。

© www.soinside.com 2019 - 2024. All rights reserved.