2

I am receiving some XML that looks like this.

<?xml version="1.0"?>
<parent xmlns="urn:place-com:spec.2004">
  <childA xmlns="">123</childA>
  <childB xmlns="">456</childB>
</parent>

I'm deserializing it into a class with C#'s XmlSerializer. It works, except the blank child namespaces are giving me trouble. Their properties in the class are null.

I understand the blank namespace puts the element in the global namespace. Probably not what is intended, but what I am receiving none the less.

If I manually delete the xmlns="" attribute from the child element it works. If I fill out the attribute with xmlns="testNamespace" and add the following attribute to the property in the class, it works.

[XmlElement(Namespace="testNamespace")]
public string childA
{ ... }

However, leaving the XML as is, and adding the following attribute does not work.

[XmlElement(Namespace="")]

How can I specify that an element has a blank namespace for deserialization?

Rob Mosher
  • 509
  • 3
  • 13
  • One thing you could do is ignore namespaces when reading the xml file, this can be done on the XML reader instance: `XmlTextReader.Namespaces = false;` – Lennart Stoop Apr 27 '18 at 14:01
  • 1
    Can you provide a [mcve]? Because as you can see [from this fidde](https://dotnetfiddle.net/ZubxTo), what you've suggested seems to work fine. – Charles Mager Apr 27 '18 at 14:13
  • The terminology "global namespace" is incorrect. Technically these elements are in no namespace. Beyond that, I'm not familiar with C# deserialization so I can't help you much. – Michael Kay Apr 27 '18 at 14:47
  • @CharlesMager Apparently I cannot provide an example. What works in .Net Fiddle breaks in VS. Maybe because I'm targeting 4.6? Though adding the name in XmlElement makes it work (there's no case difference in my code so it wasn't necessary if the namespaces matched). I'll provide an example if I can figure out how to get the same result in Fiddle. – Rob Mosher Apr 27 '18 at 14:52

1 Answers1

1

For the xml presented in question the following class works perfectly.

[XmlRoot("parent", Namespace = "urn:place-com:spec.2004", IsNullable = false)]
public class Parent
{
    [XmlElement("childA", Namespace = "")]
    public string ChildA { get; set; }

    [XmlElement("childB", Namespace = "")]
    public string ChildB { get; set; }
}
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49