6

有没有一种简单的方法可以从 XML 根元素中删除命名空间。我试过了

[XmlRootAttribute("MCP", Namespace = "", IsNullable = false)]    

在可序列化的类上。但是没有用。仍然得到相同的结果。

样本类

[Serializable]
[XmlRootAttribute("MCP", Namespace = "", IsNullable = false)]    
public class BINDRequest
{
    public BINDRequest()
    {

    }
    [XmlAttribute]
    public string CLIENT_REQUEST_ID { get; set; }

    public BINDRequestBody BIND { get; set; }

}

结果 xml

<?xml version="1.0" encoding="utf-8"?>
<MCP xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" CLIENT_REQUEST_ID="1">
  <BIND CLIENT_ID="test" PASSWORD="test" />
</MCP>

我不明白在 XmlRootAttribute 中指定 namsespace 有什么用?

4

1 回答 1

17

试试这个:

public class BINDRequest
{
    [XmlAttribute]
    public string CLIENT_REQUEST_ID { get; set; }
}

class Program
{
    static void Main()
    {
        var request = new BINDRequest
        {
            CLIENT_REQUEST_ID = "123"
        };
        var serializer = new XmlSerializer(request.GetType());
        var xmlnsEmpty = new XmlSerializerNamespaces();
        xmlnsEmpty.Add("", "");
        using (var writer = XmlWriter.Create("result.xml"))
        {
            serializer.Serialize(writer, request, xmlnsEmpty);
        }
    }
}
于 2010-09-13T09:26:19.733 回答