Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
The .NET Framework supplies a metadata attribute to get rid of
the surrounding element when we serialize an object derived from the XmlNode
class. Attaching the XmlAnyElement attribute to a field instructs Serialize()
to skip the enclosing element and write XML content of an XmlNode directly to
the output. When we attach the attribute to the instruction field from the
class above
[XmlAnyElement]
public XmlProcessingInstruction Instruction;
the instruction element is no longer part of the output.
<?xml version="1.0" encoding="utf-8"?>
<CarWithPI …>
<?park and lock?>
</CarWithPI>
When we attach more than one XmlAnyElementAttribute inside a
class we have to assign a different name to each instance, otherwise the
XmlSerializer constructor cannot keep all the different instances apart and
throws an exception. The XmlSerializer ignores the provided name unless the
attribute is attached to a field of type XmlElement or XmlElement[]. In those
cases, named XmlAnyElement attributes restrict the fields to element with the
names specified by the attached attribute(s). The XmlSerializer will throw an
exception to enforce this restriction whenever it detects a mismatch.
Accessing XML nodes when we deserialize objects from an XML
document does not work as well as creating them through serialization. Of all
the XmlNode derived classed, the XmlSerializer deserializes only entity
references and elements. It ignores comments, processing instructions and
documents, regardless if we attach an XmlAnyElement attribute. It also
deserializes fields of type XmlElement, but they play a special role as we will
see in the next section.
These limitations are not a show stopper given the
XmlSerializer’s focus of data-driven applications, since neither comments nor
processing instructions are part of the XSD type system. Yet, it is interesting
to note that we can serialize XmlNode derived objects to create additional XML
content, but we cannot access them through deserialization. Being able to
produce literal XML and declare fields of type XmlElement to allow for increased
flexibility parsing XML documents also has a special application as we see in
the following section.