2

I've got test xml file that looks like this:

<Person>
  <ContactInfo>
   ...
  <ContactInfo>
</Person>

When I'm trying to deserialize, everything works fine. But the problem is that sometimes the structure of this xml file is different - xml namespaces are added sometimes.

<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema"    
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <ContactInfo>
   ...
  <ContactInfo>
</Person>

And now when I'm serializing, I get IOnvalidOperationException: "There is an error in XML document (1, 2)". The inner exception message says <Person xmlns='http://tempuri.org/PaymentInformationXml.xsd'> was not expected.

So could anyone help me with this?

Filburt
  • 16,951
  • 12
  • 63
  • 111
user970694
  • 109
  • 3
  • 7
  • What are you using to deserialize? – Jim Mischel Oct 11 '11 at 18:39
  • Your example XML and the error message are not consistent; the xsi/xsd are just namespace aliases - they don't change anything. You can pretty-much ignore those two. However, `xmlns='...blah...'` is **very** important. Please clarify: is this in your XML or not? If it is, you must tell XmlSerializer in advance – Marc Gravell Oct 11 '11 at 18:48

3 Answers3

6

A namespace is fundamental in XML (unlike namespaces which are interchangeable). If Person is in that namespace, you must tell it:

[XmlRoot(Namespace="http://tempuri.org/PaymentInformationXml.xsd")]
public class Person {...}
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
1

Check out XmlSerializerNamespaces.

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

Controlling the default namespace can be done directly on the XmlSerializer:

XmlSerializer xs = new XmlSerializer(typeof(Person), "http://tempuri.org/PaymentInformationXml.xsd");

... but your question is a little unclear about where the problem comes from.

Check your Person classes [XmlType] attribute:

[XmlType(Namespace="http://tempuri.org/PaymentInformationXml.xsd")]
public class Person
{
    //...
}

The namespace for your Person type needs to be consistent with the one you use when serializing.

Filburt
  • 16,951
  • 12
  • 63
  • 111
1

there's an article about xml here

And i also stumbled accros this piece of code: (very helpfull)

XmlDocument stripDocumentNamespace(XmlDocument oldDom)
{
// Remove all xmlns:* instances from the passed XmlDocument
// to simplify our xpath expressions.
XmlDocument newDom = new XmlDocument();
newDom.LoadXml(System.Text.RegularExpressions.Regex.Replace(
oldDom.OuterXml, @"(xmlns:?[^=]*=[""][^""]*[""])", "",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline)
);
return newDom;
} 

hope this could help

LPunker
  • 603
  • 4
  • 6