2

嗨,我有 3 个这样的课程:

public abstract class XmlNs
{
    public const string XmlnsAttribute = "urn:ebay:apis:eBLBaseComponents";
}


[Serializable]
public class BulkDataExchangeRequests : XmlNs
{
    [XmlAttribute("xmlns")]
    public string XmlNs = XmlnsAttribute;
    [XmlElement("Header")]
    public Header Header { get; set; }
    [XmlElement("AddFixedPriceItemRequest")]
    public List<AddFixedPriceItemRequest> ListAddFixedPriceItemRequest { get; set; }
}

[Serializable]
public class AddFixedPriceItemRequest : XmlNs
{
    [XmlElement("ErrorLanguage")]
    public string ErrorLanguage { get; set; }
    [XmlElement("WarningLevel")]
    public string WarningLevel { get; set; }
    [XmlElement("Version")]
    public string Version { get; set; }
    [XmlElement("Item")]
    public ItemType Item { get; set; }
    [XmlAttribute("xmlns")]
    public string XmlNs = XmlnsAttribute;
}

问题是,当我序列化对象时,我得到了正确的 xml,但 AddFixedPriceItemRequest 项中没有 xmlns 属性,而在 BulkDataExchangeRequests 中,xmlns 被正确写入......

任何帮助将不胜感激...

4

1 回答 1

2

您正在嵌套元素,并且嵌套元素与其父元素位于相同的命名空间中,如果您未指定其他任何内容。因此,实际上您的序列化程序再次输出该xmlns属性是正确的,因为它不是必需的。

看:

<root xmlns="my-namespace">
    <element>this is also in the namespace "my-namespace" without further declaration</element>
    <so><are><child><elements></elements></child></are></so>
</root>


编辑:尽管 eBay 显然不符合这里的标准,但有一个解决方案!您可以以非常方便的方式为 .NET xml 序列化程序声明命名空间,并且保留这​​些声明,即使它们重复:

[Serializable]
public class BulkDataExchangeRequests : XmlNs
{
    [XmlElement("Header")]
    public Header Header { get; set; }
    [XmlElement("AddFixedPriceItemRequest")]
    public List<AddFixedPriceItemRequest> ListAddFixedPriceItemRequest { get; set; }

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new System.Xml.XmlQualifiedName[] { new System.Xml.XmlQualifiedName("", XmlnsAttribute) });
}

[Serializable]
public class AddFixedPriceItemRequest : XmlNs
{
    [XmlElement("ErrorLanguage")]
    public string ErrorLanguage { get; set; }
    [XmlElement("WarningLevel")]
    public string WarningLevel { get; set; }
    [XmlElement("Version")]
    public string Version { get; set; }
    [XmlElement("Item")]
    public ItemType Item { get; set; }

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new System.Xml.XmlQualifiedName[] { new System.Xml.XmlQualifiedName("", XmlnsAttribute) });
}

输出如预期:

<?xml version="1.0" encoding="utf-16"?>
<BulkDataExchangeRequests xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:ebay:apis:eBLBaseComponents">
  <AddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents" />
  <AddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents" />
</BulkDataExchangeRequests>

相关文件:

System.Xml.Serialization.XmlNamespaceDeclarations System.Xml.Serialization.XmlSerializerNamespaces

于 2013-07-30T12:34:30.183 回答