简体   繁体   中英

Optionally omit namespace from xml on deserialization?

I want the option to omit the xmlns:xsi, xmlns:xsd and xmlns attributes from xml content. When doing so deserialization is failing.

This is the xsd definition:

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema id="CSVDataPluginConfig"
    targetNamespace="http://tempuri.org/CSVDataPluginConfig.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/CSVDataPluginConfig.xsd"
    xmlns:mstns="http://tempuri.org/CSVDataPluginConfig.xsd"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
>
  <xsd:element name="CSVDataPluginConfig" type="CSVDataPluginConfig"/>
  <xsd:complexType name="CSVDataPluginConfig">
  ...
  </xsd:complexType>
</xsd:schema>

The xsd.exe code generator is giving this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(
    Namespace="http://tempuri.org/CSVDataPluginConfig.xsd")]
[System.Xml.Serialization.XmlRootAttribute(
    Namespace="http://tempuri.org/CSVDataPluginConfin.xsd", IsNullable=false)]
public partial class CSVDataPluginConfig {
}

This is the sample of xml content that deserializes successfully:

<?xml version="1.0" encoding="utf-16"?>
<CSVDataPluginConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="http://tempuri.org/CSVDataPluginConfig.xsd">
...
</CSVDataPluginConfig>

For simplicity and making it easier to handwrite the xml, I want to be able to successfully deserialize the following:

<CSVDataPluginConfig>
...
</CSVDataPluginConfig>

I am deserializing using this extension method:

    public static T DeserializeXML<T>(this string xml)
    {
        T obj;
        using (StringReader reader = new StringReader(xml))
        {
            obj = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
            reader.Close();
        }
        return obj;
    }

Using Visual Studio 2008, what are my options, and what is the best option?

Sorry, you don't actually have an option.

The author of the XML is (properly) using namespaces. That means the XML is in a namespace, and you have to use it.

In fact, with a good XML Editor, the namespaces make it easier to hand-enter it. The namespaces map to a schema, and the schema can inform the XML editor how to help you with the data entry. Try the XML editor in Visual Studio 2010 and you'll see what I mean. Just make sure that the schema is available (maybe in the same project), and it will go as far as filling in the XML with placeholders as soon as you type <CSV TAB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM