从XMLSerializer中删除命名空间标记(xmlns :)

时间:2011-12-22 07:29:20

标签: c# xml xml-serialization

我想在我的C#代码中生成以下xml输出:

<?xml version="1.0" encoding="utf-16"?>
<CallConnectReq Xmlns="urn:interno-com:ns:a9c" reqId="9" msgNb="2">
  <LocalCallId>0</LocalCallId>
</CallConnectReq>

现在我实现如下:

var xnameSpace = new XmlSerializerNamespaces();
                xnameSpace.Add("Xmlns", Constants.XmlNameSpaceValue);
                var xmlSerializer = new XmlSerializer(objToSerialize.GetType());
                var stringWriter = new StringWriter();
                xmlSerializer.Serialize(stringWriter, objToSerialize, xnameSpace);
                return stringWriter.ToString().**Replace("xmlns:","");**

但我想删除“xmlns:”标记而不使用Replace()方法。 有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

添加 默认命名空间:

var xnameSpace = new XmlSerializerNamespaces();
xnameSpace.Add("", "urn:interno-com:ns:a9c");
var ser = new XmlSerializer(typeof (CallConnectRequest));
ser.Serialize(destination, new CallConnectRequest(), xnameSpace);

使用:

[XmlRoot("CallConnectReq", Namespace = "urn:interno-com:ns:a9c")]
public class CallConnectRequest {}

答案 1 :(得分:1)

如果你真的想要Xmlns(重申,我强烈认为这是xmlns的错字,如果不是,那就是一个错误的选择混淆),然后:

var xnameSpace = new XmlSerializerNamespaces();
xnameSpace.Add("", "");
var ser = new XmlSerializer(typeof (CallConnectRequest));
ser.Serialize(destination, new CallConnectRequest {
    RequestId = 9,
    MessageNumber = 2,
    LocalCallId = 0
}, xnameSpace);

使用:

[XmlRoot("CallConnectReq")]
public class CallConnectRequest {
    [XmlAttribute("Xmlns"), Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string XmlNamespace {
        get { return "urn:interno-com:ns:a9c";} set { }
    }
    [XmlAttribute("reqId")]
    public int RequestId { get; set; }
    [XmlAttribute("msbNb")]
    public int MessageNumber { get; set; }

    [XmlElement("LocalCallId")]
    public int LocalCallId { get; set; }
}

写道:

<?xml version="1.0" encoding="ibm850"?>
<CallConnectReq Xmlns="urn:interno-com:ns:a9c" reqId="9" msbNb="2">
  <LocalCallId>0</LocalCallId>
</CallConnectReq>