0

我希望选择从 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,我有哪些选择,最好的选择是什么?

4

1 回答 1

0

对不起,你实际上没有选择。

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

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

于 2011-05-06T16:54:57.553 回答