简体   繁体   English

如何从XML根元素中删除命名空间?

[英]how to remove namespace from XML root element?

is there a simple way to remove the namespace from the XML root element. 是否有一种从XML根元素中删除命名空间的简单方法。 I have tried with 我试过了

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

on the serializable class. 在序列化类上。 But no use. 但没用。 still getting the same result. 仍然得到相同的结果。

sample class 样本班

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

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

    public BINDRequestBody BIND { get; set; }

}

result xml 结果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>

i don't understand then whats the use of specifying namsespace in XmlRootAttribute?? 我不明白那么在XmlRootAttribute中使用指定namsespace是什么意思?

Try this: 试试这个:

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM