其他分享
首页 > 其他分享> > 冒号字符在XML元素序列化过程中被编码为x003A

冒号字符在XML元素序列化过程中被编码为x003A

作者:互联网

在实例化对象并使用XmlSerializer进行序列化之后,我将类型定义为Example,如下所示,我得到的是x003A而不是冒号:

这是我的代码:

 public class Example
        {
            [XmlElement("Node1")]
            public string Node1 { get; set; }
            [XmlElement("rd:Node2")]
            public string Node2 { get; set; }
        }

序列化代码

 Example example = new Example { Node1 = "value1", Node2 = "value2" };

            XmlSerializerNamespaces namespaceSerializer = new XmlSerializerNamespaces(); 
            namespaceSerializer.Add("rd", @"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Example));
            string path = System.Windows.Forms.Application.StartupPath + "//example.xml";
            using (StreamWriter writer = new StreamWriter(path))
            {
                serializer.Serialize(writer, example, namespaceSerializer);
            }

预期结果

<?xml version="1.0" encoding="utf-8"?>
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Node1>value1</Node1>
  <rd:Node2>value2</rd:Node2>
</Example>

实际结果:

<?xml version="1.0" encoding="utf-8"?>
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Node1>value1</Node1>
  <rd_x003A_Node2>value2</rd_x003A_Node2>
</Example>

在这方面的任何帮助和指导都将不胜感激.提前致谢!

解决方法:

您必须这样做:

public class Example {
    [XmlElement("Node1")]
    public string Node1 { get; set; }
    // define namespace like this, not with a prefix
    [XmlElement("Node2", Namespace = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")]
    public string Node2 { get; set; }
}

然后在序列化时:

var serializer = new XmlSerializer(typeof(Example));
var ns = new XmlSerializerNamespaces();
// map prefix to namespace like this
ns.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
var ms = new MemoryStream();      
// use namespaces while serializing
serializer.Serialize(ms, new Example {
    Node1 = "node1",
    Node2 = "node2"
}, ns);

标签:serialization,encryption,xml,c,xmlserializer
来源: https://codeday.me/bug/20191025/1929123.html