【问题标题】:How to avoid encoding of special characters in xmlroot如何避免在 xmlroot 中编码特殊字符
【发布时间】:2015-10-20 12:58:31
【问题描述】:

我尝试使用不同的 xmlrootname "ns1:BatchChanges" 序列化 JTDChanges 类,但在将其写入文件时序列化后,“ns1:BatchChanges”被编码为“ns1_x003A_BatchChanges”。

这是我的课

[ Serializable, XmlRoot("ns1:BatchChanges") ]
    public class JTDChanges
    {
        [XmlElement("OrgUnitChanges")]
        public List<OrgUnitStage> CustomerChanges = new List<OrgUnitStage>();
    } 

谁能建议我如何避免编码?

【问题讨论】:

    标签: c# xml xml-serialization xmlserializer


    【解决方案1】:

    相信您正在寻找Xml Namespace functions

    [Serializable, XmlRoot("BatchChanges, Namespace = "http://www.w3.org/XML/2008/xsdl-exx/ns1") ]
    public class JTDChanges
    {
        [XmlElement("OrgUnitChanges")]
        public List<OrgUnitStage> CustomerChanges = new List<OrgUnitStage>();
    } 
    

    现在在这真正起作用之前,你还需要告诉你的序列化器使用这个命名空间

    // Create a name space prefix
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("ns1", "ttp://www.w3.org/XML/2008/xsdl-exx/ns1");
    
    // Create a serializer
    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(this.GetType());
    
    // And pass the namespace along as param
    ser.Serialize(writer, this, ns)
    

    至于测试,您可以声明以下内容

     [XmlElement(ElementName = "point", Namespace = "http://www.w3.org/XML/2008/xsdl-exx/ns1")]
    

    这会导致 &lt;ns1:point&gt;(whatever the values were you declared it upon)&lt;/ns1:point&gt;

    【讨论】:

    • 谢谢,成功了。但它也将我的所有 xml 节点从 OrgUnitChanges 转换为 ns1:OrgUnitChanges。我希望 ns1 仅附加到根节点。
    • @SriHarsha 在 SO which explain you how to do that 上有很多帖子。如果此答案对您有所帮助,请不要忘记将其作为答案/投票给其他人查看
    猜你喜欢
    • 2014-03-31
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多