【发布时间】:2018-08-22 14:59:23
【问题描述】:
下面是我正在编写的一些 XML 示例。这是有效的 XML,但为了减小文件大小,我想删除标签并简单地将值写入属性中。
我目前拥有的
<custom-attributes>
<custom-attribute attribute-id="isDropShip">
<value>false</value>
</custom-attribute>
<custom-attribute attribute-id="restrictPayPal">
<value>false</value>
</custom-attribute>
</custom-attributes>
我希望拥有的东西
<custom-attributes>
<custom-attribute attribute-id="isDropShip">false</custom-attribute>
<custom-attribute attribute-id="restrictPayPal">false</custom-attribute>
</custom-attributes>
列表持有自定义属性和扩展列表添加方法
List<sharedTypeSiteSpecificCustomAttribute> custom = new List<sharedTypeSiteSpecificCustomAttribute>();
custom.AddAttribute("isDropShip", dropship);
custom.AddAttribute("restrictPayPal", subClass);
添加方法扩展
public static class ListExtensions
{
public static void AddAttribute(this List<sharedTypeSiteSpecificCustomAttribute> list, string id, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return;
}
list.Add(new sharedTypeSiteSpecificCustomAttribute { attributeid = id, value = new[] { value } });
}
}
XSD sharedTypeSiteSpecificCustomAttribute 代码
public partial class sharedTypeSiteSpecificCustomAttribute : sharedTypeCustomAttribute
{
private string siteidField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute("site-id")]
public string siteid
{
get
{
return this.siteidField;
}
set
{
this.siteidField = value;
}
}
}
sharedTypeCustomAttribute 代码
public partial class sharedTypeCustomAttribute
{
private string[] valueField;
private string[] textField;
private string attributeidField;
private string langField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("value")]
public string[] value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string[] Text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute("attribute-id")]
public string attributeid
{
get
{
return this.attributeidField;
}
set
{
this.attributeidField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.w3.org/XML/1998/namespace")]
public string lang
{
get
{
return this.langField;
}
set
{
this.langField = value;
}
}
}
感谢任何帮助。这对我来说是新的,我只是想学习最佳实践和方法。
【问题讨论】:
-
@Y.S 这个答案似乎很好地解释了每种风格的优缺点,但这不是我的问题。我特别问如何删除
... 标记并内联写入值。