【问题标题】:Optionally omit namespace from xml on deserialization?可选地在反序列化时从 xml 中省略命名空间?
【发布时间】:2011-05-07 01:02:28
【问题描述】:

我想要从 xml 内容中省略 xmlns:xsi、xmlns:xsd 和 xmlns 属性的选项。这样做时,反序列化会失败。

这是 xsd 的定义:

<?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>

xsd.exe 代码生成器给出这个:

[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 {
}

这是反序列化成功的xml内容示例:

<?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>

为了简单起见并更容易手写 xml,我希望能够成功反序列化以下内容:

<CSVDataPluginConfig>
...
</CSVDataPluginConfig>

我正在使用这种扩展方法进行反序列化:

    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;
    }

使用 Visual Studio 2008,我有哪些选择,最好的选择是什么?

【问题讨论】:

标签: c# xml-serialization xml-namespaces xsd.exe


【解决方案1】:

抱歉,您实际上没有选项。

XML 的作者(正确地)使用命名空间。这意味着 XML 位于命名空间中,您必须使用它。

事实上,使用一个好的 XML 编辑器,命名空间使手动输入它更容易。命名空间映射到一个模式,该模式可以通知 XML 编辑器如何帮助您进行数据输入。试试 Visual Studio 2010 中的 XML 编辑器,你就会明白我的意思了。只需确保架构可用(可能在同一个项目中),只要您键入 &lt;CSVTAB

,它就会使用占位符填充 XML

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 2021-02-17
    • 2015-11-03
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    相关资源
    最近更新 更多