我想在我的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()方法。
有什么办法吗?

最佳答案

如果您确实想要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>

关于c# - 从XMLSerializer删除 namespace 标签(xmlns :),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8600658/

10-11 18:11