How do I deserialize XML namespaces in C# (System.Xml.Serialization)?

后端 未结 2 755
鱼传尺愫
鱼传尺愫 2021-01-13 06:43

I am just putting the finishing touches to my Zthes format deserializer (System.Xml.Serialization) which uses the namespace \"dc\" in the element \"thes\". All \"term\" elem

相关标签:
2条回答
  • 2021-01-13 06:48
    [XmlElement("someElement", Namespace="namespace")]
    public string SomeElement;
    

    Addendum: Make sure "namespace" is the full URI of the namespace, not just the prefix.

    0 讨论(0)
  • 2021-01-13 06:50

    Here's a quick sample for you...

    [XmlRoot("myObject")]
    public class MyObject
    {
        [XmlElement("myProp", Namespace = "http://www.whited.us")]
        public string MyProp { get; set; }
    
        [XmlAttribute("myOther", Namespace = "http://www.whited.us")]
        public string MyOther { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var xnames = new XmlSerializerNamespaces();
            xnames.Add("w", "http://www.whited.us");
            var xser = new XmlSerializer(typeof(MyObject));
            using (var ms = new MemoryStream())
            {
                var myObj = new MyObject()
                {
                    MyProp = "Hello",
                    MyOther = "World"
                };
                xser.Serialize(ms, myObj, xnames);
                var res = Encoding.ASCII.GetString(ms.ToArray());
                /*
                    <?xml version="1.0"?>
                    <myObject xmlns:w="http://www.whited.us" w:myOther="World">
                      <w:myProp>Hello</w:myProp>
                    </myObject>
                 */
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题