gpt4 book ai didi

c# - 使用 C# 允许在 XML 序列化中重复节点名称

转载 作者:数据小太阳 更新时间:2023-10-29 01:58:39 25 4
gpt4 key购买 nike

我正在尝试使用 C# 序列化具有重复节点名称的对象,我需要这样做的原因是因为我正在构建一个使用第三方 API 的库。

我需要构建的请求如下所示。

<DATASET>
<SITE_ID>123</SITE_ID>
<DATA type=“name”>Secondary List</DATA>
<DATA type="extra" id="CLICKTHRU_URL">http://my.domain.com/</DATA>
<DATA type="extra" id="REPLY_FORWARD_EMAIL">support@my.domain.com</DATA>
<DATA type="extra" id="REPLY_FROM_EMAIL">forward@my.domain.com</DATA>
<DATA type="extra" id="REPLY_FROM_NAME">8@yahoo.com</DATA>
<DATA type="extra" id="REPLY_FORWARD_SUBJECT">Customer Replies</DATA>
<DATA type="extra" id="HANDLE_UNSUBSCRIBE"></DATA>
<DATA type="extra" id="HANDLE_AUTOREPLY"></DATA>
<DATA type="extra" id="FOOTER_TEXT">Confidentiality agreement…</DATA>
<DATA type="extra" id="FOOTER_HTML"> Confidentiality agreement…</DATA>
</DATASET>

我的方法是创建一个表示请求并使用 XML 序列化属性的类,该类如下所示:

[XmlRoot("DataSet")]
public class AddListCallHolder : BaseCallHolder
{
private BaseAttributeHolder _name = new BaseAttributeHolder(type: "");

[XmlElement("DATA")]
public BaseAttributeHolder Name
{
get { return _name; }
set { _name = value; }
}

private BaseAttributeHolder _clickthruUrl = new BaseAttributeHolder(id: "CLICKTHRU_URL");

[XmlElement("DATA")]
public BaseAttributeHolder CLICKTHRU_URL
{
get { return _clickthruUrl; }
set { _clickthruUrl = value; }
}
}

属性的基类是:

public class BaseAttributeHolder
{
[XmlAttribute("type")]
public string Type { get; set; }

[XmlAttribute("id")]
public string Id { get; set; }

[XmlText]
public string Value { get; set; }

public BaseAttributeHolder(string value, string id, string type = "extra")
{
Type = type;
Value = value;
Id = id;
}

public BaseAttributeHolder(string id, string type = "extra")
{
Type = type;
Id = id;
}

public BaseAttributeHolder(string type = "extra")
{
Type = type;
}

public BaseAttributeHolder()
{

}
}

当我尝试序列化和反对时,我得到了这个错误:

The XML element 'DATA' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

是否有任何解决方法来序列化此对象或获取请求的结构。

最佳答案

使用数组或列表反序列化所有<DATA>怎么样?的,然后添加对该数组进行操作的属性?

  [XmlRoot("DataSet")]
public class AddListCallHolder
{
[XmlArrayItem(typeof(BaseAttributeHolder), ElementName = "DATA")]
public BaseAttributeHolder[] data
{
get;
set;
}

[XmlIgnore]
public BaseAttributeHolder Name
{
get
{
return data.FirstOrDefault(d => d.Type == "name");
}
}

[XmlIgnore]
public BaseAttributeHolder CLICKTHRU_URL
{
get
{
return data.FirstOrDefault(d => d.Type == "extra" && d.Id == "CLICKTHRU_URL");
}
}
}

我想你也能想出二传手。

关于c# - 使用 C# 允许在 XML 序列化中重复节点名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8496958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com