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

Colon character getting encoded to x003A in xml element serialization process

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

这是我的代码:

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

对于此类任务尽量避免使用基于属性的方法。

[XmlElement("rd:Node2")] //this will create rd_x003A_Node2

我建议使用序列化功能。看看https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializernamespaces?view=net-5.0