您好我有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被正确写入....
任何帮助都将非常感谢...
答案 0 :(得分: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