XmlSerializer not reading some attributes with redundant explicit namespace

Hello all,

I'm trying to use annotation-based automatic XML serialization of my
..NET-classes in order to exchange XML with other platforms. So far my
class looks like this:

[XmlRoot(ElementName="thing", Namespace="http://eins")]
public class ExampleXmlSerializable
{
    [XmlAttribute(AttributeName = "price", Namespace = "http://eins")]
    public string Price { get; set; }
}

As you can see, the attribute 'price' is in the 'http://eins' namespace.
However, when I feed the following XML into the XmlSerializer:

  <ns0:thing ns0:price='much' xmlns:ns0='http://eins'/>

the 'Price' property of my instance is null.
When I deserialize

  <ns0:thing price='much' xmlns:ns0='http://eins'/>

the 'Price' property is correctly filled with 'much'. The only
difference is that the 'price' attribute in the first example has a
superfluous but correct namespace prefix.

As far as I can see, .NET fails to deserialize a valid XML
representation. Am I missing something?

--Konrad




PS:
My XML format is supposed to be a cross-platform exchange format, so I
can't easily add house rules like "please omit redundant ns prefixes on
attributes" to the format specification.

I'm using .NET 3.5.

The problem is visible in this NUnit test, where TestImplicitAttributeNS
passes and TestExplicitAttributeNS fails:

[TestFixture]
public class TestDotNetXmlSerializerVsAttributeNamespaces
{
    [Test]
    public void TestImplicitAttributeNS()
    {
        string xml =
"<ns0:thing price='much' xmlns:ns0='http://eins'/>";
        XmlSerializer xmlser =
            new XmlSerializer(typeof(ExampleXmlSerializable));
        ExampleXmlSerializable fromxml = ((ExampleXmlSerializable)
               (xmlser.Deserialize(new StringReader(xml))));
         Assert.AreEqual("much", fromxml.Price); // passes
    }
    [Test]
     public void TestExplicitAttributeNS()
     {
        string xml =
"<ns0:thing ns0:price='much' xmlns:ns0='http://eins'/>";
        XmlSerializer xmlser =
              new XmlSerializer(typeof(ExampleXmlSerializable));
        ExampleXmlSerializable fromxml = ((ExampleXmlSerializable)
                (xmlser.Deserialize(new StringReader(xml))));
        Assert.AreEqual("much", fromxml.Price); // fails
      }
  }

0
10/15/2008 11:40:53 AM
dotnet.xml 7266 articles. 0 followers. Follow

2 Replies
665 Views

Similar Articles

[PageSpeed] 27

Konrad Anton wrote:

> [XmlRoot(ElementName="thing", Namespace="http://eins")]
> public class ExampleXmlSerializable
> {
>     [XmlAttribute(AttributeName = "price", Namespace = "http://eins")]

You need to set the Form here too e.g.
    [XmlAttribute(AttributeName = "price", Namespace = "http://eins", 
Form = System.Xml.Schema.XmlSchemaForm.Qualified)]


-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1778)
10/15/2008 12:07:35 PM
Martin Honnen wrote:
> Konrad Anton wrote:
>> [XmlRoot(ElementName="thing", Namespace="http://eins")]
>> public class ExampleXmlSerializable
>> {
>>     [XmlAttribute(AttributeName = "price", Namespace = "http://eins")]
> 
> You need to set the Form here too e.g.
>    [XmlAttribute(AttributeName = "price", Namespace = "http://eins",
> Form = System.Xml.Schema.XmlSchemaForm.Qualified)]

Thanks for the quick answer.

I was unaware of the small print in the interaction between XMLSchema
and namespaces, so my initial assumption (that my two documents were
equally valid for every notion of validity) was wrong; there apparently
is an XMLSchema which can tell them apart by means of xsd:attributeForm
and friends.

So I'll just publish an XMLSchema of my format, and the problem is gone.

--Konrad
0
10/15/2008 1:14:57 PM
Reply:

Similar Artilces:

How to create a read-only database
Hi, I have set up a simple ordering system at my workplace using Exce forms. Using template wizard with data tracking all orders using thi form are stored in a database. I like this database to be read-only, s everyone can see the orders placed without messing up the database However, if I make the database read-only, the template wizard i unable to add new orders. How do I get around this problem? Fo instance, is it possible to make an automatic copy of the databas everytime it is changed which is read-only ?? Thnx Richar -- Rajjansse -----------------------------------------------------...

[OT?] Reading hardware from thread
Hello, This might be a slightly Off Topic question but I don't know where else to put it. I have a digital I/O PCI Card that I have to read at least once every 35 ms (We are using the I/O card for communicating with an PLC that has about 35 ms cycle time. I have tried using OnTimer() but it will not work with these small times. So I was thinking that I maybe could start a thread that reads the I/O card continuously in a loop and creates Events Messages when something changes. Since I haven't done anything like this before I just want to check with you guys and girls if it'...

how to recive confirmation read e-mail with e-mail router
In MSCRM with E-mail router, It�s posible receive message confirmation when an e-mail is read for the contact or account ? Thanks Valentin Collado There is no way to do this in the current version. -- Matt Wittemann http://icu-mscrm.blogspot.com "Valentin" wrote: > In MSCRM with E-mail router, It´s posible receive message confirmation when > an e-mail is read for the contact or account ? > > Thanks > > Valentin Collado > > > ...

Fields Read Only
How Do I Make Fields Read only after I saved it Thx There is no built-in support for this in the app. However, you could add javascript to the aspx page to disable the field if you want. Matt Parks MVP - Microsoft CRM ---------------------------------------- ---------------------------------------- On Mon, 15 Aug 2005 14:53:42 +0200, "Need Some Help" <Need@news.microsoft.com> wrote: How Do I Make Fields Read only after I saved it Thx ...

Where "regedit" read from..?
When I type "regedit" in the run command of the Start menu, what file Windows uses to get this information from..? I use Windows 2000, but I would like to know where this come from also from any other Windows version. Thanks; Hugo This is a windows, not an outlook question... but I think I can answer it anyway - it comes from the registry files which are stored in C:\WINDOWS\system32\config and ntuser.dat in your profile. -- Diane Poremsky [MVP - Outlook] Author, Teach Yourself Outlook 2003 in 24 Hours Coauthor, OneNote 2003 for Windows (Visual QuickStart Guide) Author, Goog...

Unable to open Excel 2002 files
I have 2 Excel 2002 files that won't open with the message they are read-only or encrypted. This is on WIN XP Pro. Prior to this happening I remember them showing a message that there was a sharing violation - I can't see how as this computer is not on a network and I am the only user anyway. I also deleted all files in my temp folders and did a re-boot. Anyway now I can't even open, delete, rename, email or move these 2 files. I have run a virus checker and carried out chkdsk. All other Excel worksheet files are fine. Anything else I can do to check the problem? It can&...

XmlSerializer Collection with Collections
Hello I got this working but it is not how I really want it, basically I have an xml file which has a root of <test> and can be filled with 3 different types of <question> elements with different attributes, all share a base set of 4, one of the question types can have children with <option> elements, this is how the xml looks after serialization.... If you notice there is an extra <SelectionList> around the <option>'s in the final <question>, how can I write my class so I don't have this extra <SelectionList> element....my class follows, you ...

XmlSerializer
I'm having a basic problem with the XmlSerializer & i'm at my wits end trying to sort it out i have a basic clas <Serializable()> Class Tes Public Name as Strin End Clas when this serializes i wan <Test><Name>Value</Name></Test the problem is if i use the XmlSerializer clas Dim t as Tes t.Name="Value Dim sb As New StringBuilde Dim sw As New StringWriter(sb Dim Serializer As New XmlSerializer(Message.GetType Serializer.Serialize(sw, t Serializer = Nothin Console.Write(sb.ToStr...

XmlSerializer and shared objects (or How to generate IDREFs using XmlSerializer)
This is a multi-part message in MIME format. ------=_NextPart_000_007F_01C34AC1.11D4FB20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am trying to find a solution that will allow me to use XmlSerializer = to serialize/deserialize a collection of objects where a given object is = shared between two or more other objects, and not create duplicate XML = representations of the shared object, but instead use IDREFs to refer to = the shared object. The XML I'm trying to produce is as follows (where "href" is an IDREF): <...

XmlSerializer and inherited objects
Hi I have a hirachy of classes which are Message(base), then FileMessage and ChatMessage (extended) I want to serialize the objects and when i am deserizaling i dont know if i am getting FileMessage or ChatMessage. So how to get that object and use it I have written following code for serialization public void Send(Message message) { NetworkStream netWorkStream=null; try { XmlSerializer serializer=new XmlSerializer(message.GetType()); netWorkStream=new NetworkStream(_clientSocket); Stream stream=(Stream)netWorkStream; serializer.Serialize(stream,message); } finally { netWorkStrea...

Unable to read file #10
I have created a small application in XL with VBA. Inadvertantly I must have changed the file extension. I now try to open the file and get the message "Unable to read file". Can someone help me get around this as a lot of work has gone into this particular project. Can i write some VBA code to get behind the scenes and open the file. Many thanks. Does this happen on just this one file? If yes, do you have a backup? Sometimes excel workbooks get corrupted. One cause is opening them from a floppy and saving to that floppy. (Instead you should use windows explorer to cop...

XMLSerializer Serialize
Iam trying to create a xml file by serializing a custom business object. Iam using a xmltextwriter, but the problem there are invalid characters at the end of the generated file anyone knows a way around it ? tia Dim myStream As New IO.MemoryStream Dim myXMLWriter As New System.Xml.XmlTextWriter(myStream, System.Text.Encoding.UTF8) myXMLWriter.Formatting = System.Xml.Formatting.Indented Dim myShipments As OrderShipments myShipments = CType(myOrder.OrderAddresses(0), COrderAddress).Shipments myShipments.ToXML(myXMLWriter) ...

read-only objects (CRM 3)
I'm building an Order workflow that's triggered by a change to Canceled status. It generate several tasks and emails, and I need it to update a custom date field on the order with the current date. The update entity portion of the workflow fails because once the order is cancelled the field is read-only. Here's the question: How to I make a specific field not read-only once the order is cancelled? -- Tracy Bourgoine, IT Analyst On Nov 5, 5:59=A0am, TracyB <Tra...@discussions.microsoft.com> wrote: > I'm building an Order workflow that's triggered by a...

I cannot read my ex-employee's pst file
Hi, all: I restored a ex-employee's pst file from my backup to my local HD. I am using OUTLOOK 2000. I tried to add another personal folder pointed to the restored pst file. But I got a message saying that it is not a personal folder file. Any help there? BTW, we are runnint Exchange 5.5 server. Thanks, alot! RIck If the ex-employee was using Outlook 2003, and created a unicode pst, you wont be able to read it with Outlook 2000. If the pst is corrupt: http://www.slipstick.com/problems/scanpst.htm On Mon, 28 Feb 2005 12:13:01 -0800, "Rick" <Rick@discussions.microsoft...

startup error message re: "problem reading reminders"
Each time I start outlook 2003 I keep getting a pop up error message stating "There was a problem reading one or more of your reminders. Some reminders may not appear. Cannot locate recurrence information for this appointment." And then the same error message pops up every few minutes in the lower right hand corner of my bottom taskbar. Very annoying. What's strange is that I never use the reminder function. Any ideas for a fix? Thanks. Jack close outlook and in the start menu, run command type outlook.exe /cleanreminders -- Diane Poremsky [MVP - Outlook] Author, Te...

Reading ruler/marker/thingy
Hi, Are you familiar with the process of using a ruler or (I'm talking about actual paper here, not a computer screen) if preferable using those rulers with a colored transparent strip in them to mark the page you're reading or proofing? As you move further in the document you mark the line your reading with the ruler. Kinda like keeping a finger pressed below the last word you've read. It makes it easy to proof against another copy when you must move back and forth between pages without getting lost. Does Word have a similar feature? Something that when click...

XmlSerializer help
Hi, I have a class: public class Note { public string name; public string information; } And i Serialize this class, but want to Serialize it to an XmlDocument which will contain many of these elements. How do i do this? Thank you, Tim. Timothy, take a look at Chris Lovett's XmlNodeWriter on www.gotdotnet.com [0]. Simply pass the node where you want to insert the serialized XML into the XmlDocument to an XmlNodeWriter and pass the XmlNodeWriter to the Serialize method. -- HTH Christoph Schittko [MVP] Software Architect, .NET Mentor [0] http://gotdotnet.com/Communit...

Read receipt in Entourage and mail
Version: 2008 Operating System: Mac OS X 10.5 (Leopard) Processor: Intel How do set the delivered and read receipt in Entourage and Mail? So that we will be inform whether the email recipient have received and read email that we sent. Outlook can do this. Thanks a bunch.... Paulina_Lo@officeformac.com wrote: > How do set the delivered and read receipt in Entourage and Mail? So > that we will be inform whether the email recipient have received and > read email that we sent. Outlook can do this. Go to Tools --> Accounts... and double-click your account. Under the Options tab ad...

read message indicator
Shouldn't the header on the messages change from bold to regular font after being read? My doesn't. Is there a setting to set? What are your settings for marking items as read? Once the focus changes? After xx seconds? Is this even active? What version of Outlook? --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. Due to the (insert latest virus name here) virus, all mail sent to my personal account will be deleted without reading. After searching google.groups.com and finding no answer, Gray asphalt (formerly NSQ) asked: | Shoul...

Thrown out of Outlook when sending or reading messages
When user tries to send or read a message he is thrown out of Outlook. He gets an access violation error and the It shuts the software down completly. ...

Problems with XmlSerializer and namespaces
I have an object, Teacher, that has a namespace. Let's call it http://foo. Teacher has a child object called Name, composed of String first, middle, last, etc. Problem I have is when I try to deserialize it. When I deserialize a single Teacher, it works when I put the namespace on the Teacher element. However, if I have just the namespace on Teacher, it will deserialize fine as Teacher. *However*, if I try to deserialize an ArrayOfTeacher, Teacher.Name doesn't deserialize (it's null); without the array, it's OK. What I wound up doing was serializing both a Teacher ...

Slow reading xml file
I'm opening an xml file with the statement XPathDocument xPathDocument = new XPathDocument(fileLocation); and then scanning the structure using an XPathNavigator. This works but loading the document is tediously slow, since the xml file can be pretty large. What is a quick alternative ? JezB wrote: > I'm opening an xml file with the statement > > XPathDocument xPathDocument = new XPathDocument(fileLocation); > > and then scanning the structure using an XPathNavigator. This works but > loading the document is tediously slow, since the xml file can be pret...

XmlSerializer and ICollection
Hello all, I have two simple classes: Item and ItemCollection. Item stores a label for the item and an instance of ItemCollection for all child items. ItemCollection just stores a collection of Items. ItemCollection implements System.Collections.ICollection. When I use XmlSerializer to serialize an instance of ItemCollection, I am unable to control the element names used to contain the item collection and the items therein. Applying XmlRootAttribute to the ItemCollection class causes an exception because it implements ICollection. I have also tried implementing IXmlSerializer in my ItemColl...

Problem reading reminders #2
This is a multi-part message in MIME format. ------=_NextPart_000_0014_01C57290.56614700 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I use MS Outlook as my email and to manage my work appointments & = reminders; without it I'm lost and in danger of missing important = meetings. For the last few weeks I've been getting the following message = whenever I start Outlook:=20 "There was a problem reading one or more of your reminders. Some = reminders may not appear. Cannot locate recurrence information for this = appointm...

XmlSerializer question
Hi, I use XmlSerializer to serialize xml string. It escapes xml special charaters, like < and > to < and >. How can I stop XmlSerializer to escape these charaters? Thanks in advance!!! Cindy Cindy wrote: > I use XmlSerializer to serialize xml string. It escapes xml special > charaters, like < and > to < and >. How can I stop XmlSerializer to escape > these charaters? If the XmlSerializer didn't escape the characters < and & (and for compatibility >), then the result would not be well-formed XML. See section 2.4 of the XML specification [1]...