XmlSerializer命名空间不可见,为什么?

时间:2012-02-17 13:28:28

标签: .net xml-namespaces xmlserializer

我有一个我要序列化的课程:

[XmlRoot(ElementName = "FileInfoMessage")]
public class Message : IMessage
{
 [XmlAttribute]
 public int Id { get; set; }

 [XmlAttribute(Namespace = "Files")]
 public Version { get; set; }
 //...
}

和我的序列化方法:

//_xmlData - string containing xml content
public void SerializeData(IMessage message, Encoding encoding)
        {
            using (var stream = new MemoryStream())
            {
                var writerSettings = new XmlWriterSettings {Encoding = encoding, OmitXmlDeclaration = false, Indent = true, NamespaceHandling = NamespaceHandling.Default };
                var writer = XmlWriter.Create(stream, writerSettings);
                var serializer = new XmlSerializer(message.GetType());
                var namespaces = new  XmlSerializerNamespaces();
                namespaces.Add("", "Files"); //if I add custom prefix, it will be visible
                serializer.Serialize(writer, message, namespaces);
                stream.Position = 0;
                _xmlData = new StreamReader(stream).ReadToEnd();
            }

我想要的是:

<?xml version="1.0" encoding="windows-1250"?>
<FileInfoMessage Id = "1" **xmlns="Files"** Version="2">
 //...
</FileInfoMessage>

但我明白了:

<?xml version="1.0" encoding="windows-1250"?>
<FileInfoMessage Id = "1" p1:Version="2" xmlns:p1="Files">
 //...
</FileInfoMessage>

如果我改变我的SerilizeMethod行: namespaces.Add(“whateverIwant”,“Files”);

我得到了:

 <?xml version="1.0" encoding="windows-1250"?>
    <FileInfoMessage Id = "1" **xmlns:whateverIwant="Files"** Version="2">
     //...
    </FileInfoMessage>

任何可能的方法来实现它?

*经过一些修改后编辑。

1 个答案:

答案 0 :(得分:0)

尝试将第一个参数的空字符串传递给namespaces.Add(“”,“Files”。据我所知,这就是诀窍。