从XMLSerializer中删除命名空间标签(xmlns:)
本文关键字:xmlns 标签 命名空间 XMLSerializer 删除 | 更新日期: 2023-09-27 18:18:38
我想在我的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()方法。有什么办法吗?
添加只需默认命名空间:
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 {}
如果您真的想要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>