【问题标题】:XmlSerializer in .NET with XmlSchemaForm.Unqualified.NET 中的 XmlSerializer 与 XmlSchemaForm.Unqualified
【发布时间】:2011-08-02 05:56:35
【问题描述】:

给定以下代码:

using System;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace XmlSerializationTest
{
    [XmlType(Namespace = "http://www.test.com")]
    public class Element
    {
        [XmlElement]
        public int X;
    }

    [XmlRoot(Namespace = "http://www.test.com")]
    public class Root
    {
        [XmlElement(Form = XmlSchemaForm.Unqualified)]
        public Element Element;
    }

    public static class Program
    {
        public static void Main(string[] args)
        {
            var root = new Root { Element = new Element { X = 1 } };
            var xmlSerializer = new XmlSerializer(typeof(Root));
            xmlSerializer.Serialize(Console.Out, root);
        }
    }
}

输出是:

<?xml version="1.0" encoding="ibm852"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.test.com">
  <Element xmlns="">
    <X xmlns="http://www.test.com">1</X>
  </Element>
</Root>

问题是为什么将 Form 属性设置为 XmlSchemaForm.Unqualified 会导致 Element 元素的命名空间被设置为 "",即使它具有与 Root 元素具有相同命名空间的 XmlTypeAttribute 属性?

这种代码(XmlSchemaForm.Unqualified 部分)是由WSCF.blue 工具生成的,它与命名空间混淆了。

【问题讨论】:

  • "unqualified" 表示来自目标命名空间的属性不需要使用命名空间前缀进行限定。所以这就是为什么你得到 xmlns="" 如果设置为合格,一切都很好。正如你所说,它来自一个自动化工具。查看工具中是否有可配置的选项。
  • @Aravind:我认为不合格意味着序列化程序不强制使用前缀(它可能会也可能不会)。但我不明白为什么它会改变元素元素的命名空间(从“test.com”到“”)!不幸的是,WSCF.blue 似乎没有正确的开关来解决这个问题。

标签: c# .net xml-serialization xml-namespaces wscf


【解决方案1】:

您可以覆盖元素类型中指定的命名空间。例如。你可以拥有

[XmlElement(Namespace="http://foo.com")]
public Element Element;

输出将是

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.test.com">
  <Element xmlns="http://foo.com">
    <X xmlns="http://www.test.com">1</X>
  </Element>
</Root>

Microsoft 对Form = XmlSchemaForm.Unqualified 的实现似乎完全等同于将Namespace 设置为""。特别是,如果您明确指定了任何其他命名空间 (MSDN reference),则不能使用它。如果你这样做,你会得到这个异常:

Unhandled Exception: System.InvalidOperationException: There was an error reflecting type 'XmlSerializationTest.Root'. ---&gt; System.InvalidOperationException: There was an error reflecting field 'Element'. ---&gt; System.InvalidOperationException: The Form property may not be 'Unqualified' when an explicit Namespace property is present.

【讨论】:

    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多