如何定义我的类结构,以便我可以在运行时为给定元素分配 XmlAttribute 文本(不是它的值)?例如,我有以下 XML,我想在其中为特定 XML 注释属性文本的每个实例定义一个唯一值,如下所示,“DEFINE_UNIQUE_FOR_EACH_INSTANCE”:
<MyXml>
<ZipCode DEFINE_UNIQUE_FOR_EACH_INSTANCE="Postal Code">90210</ZipCode>
<State DEFINE_UNIQUE_FOR_EACH_INSTANCE="US State">CA</State>
</MyXml>
所以我想得到类似的东西:
<MyXml>
<ZipCode labelText="Postal Code">90210</ZipCode>
<State defaultValue="US State">CA</State>
</MyXml>
这是我定义上述第一个 XML 的类定义:
[XmlRootAttribute]
public class MyXml
{
public XmlValueAndAttribute ZipCode { get; set; }
public XmlValueAndAttribute State { get; set; }
public MyXml()
{
ZipCode = new XmlValueAndAttribute(); State = new XmlValueAndAttribute();
}
}
和
public class XmlValueAndAttribute
{
[XmlAttribute("DEFINE_UNIQUE_FOR_EACH_INSTANCE")]
public string AttributeValue { get; set; }
[XmlText]
public string Value { get; set; }
public XmlValueAndAttribute() { }
public XmlValueAndAttribute(string value, string attribute)
{
Value = value;
AttributeValue = attribute;
}
}
以及类的用法。请注意注释掉的代码,指出我想如何进行属性文本分配:
static void Main(string[] args)
{
MyXml xml = new MyXml();
xml.ZipCode = new XmlValueAndAttribute("90210", "Postal Code" /*, "labelText"*/ )
xml.State = new XmlValueAndAttribute("CA", "US State" /*"defaultValue"*/);
XmlSerializer x = new XmlSerializer(xml.GetType());
var xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");
x.Serialize(Console.Out, xml, xmlnsEmpty);
Console.ReadKey();
}
谢谢。
请您参考如下方法:
您可以通过让您的XmlValueAndAttribute 类实现IXmlSerializable 来做到这一点:
public class XmlValueAndAttribute : IXmlSerializable
{
public string AttributeName { get; set; }
public string AttributeValue { get; set; }
public string Value { get; set; }
public XmlValueAndAttribute() { }
public XmlValueAndAttribute(string value, string attribute, string attributeName)
{
Value = value;
AttributeValue = attribute;
AttributeName = attributeName;
}
#region IXmlSerializable Members
public XmlSchema GetSchema()
{
return null;
}
static XName nilName = XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance");
public void ReadXml(XmlReader reader)
{
using (var subReader = reader.ReadSubtree())
{
var element = XElement.Load(subReader);
reader.Read(); // Advance past the end of the element.
if (element == null)
return;
Value = (bool?)element.Attribute(nilName) == true ? null : element.Value;
var attr = element.Attributes().Where(a => a.Name != nilName && !a.IsNamespaceDeclaration).FirstOrDefault();
if (attr != null)
{
AttributeName = XmlConvert.DecodeName(attr.Name.LocalName);
AttributeValue = attr.Value;
}
}
}
public void WriteXml(XmlWriter writer)
{
if (!string.IsNullOrEmpty(AttributeName))
writer.WriteAttributeString(XmlConvert.EncodeLocalName(AttributeName), AttributeValue);
if (Value == null)
writer.WriteAttributeString("xsi", nilName.LocalName, nilName.Namespace.ToString(), XmlConvert.ToString(true));
else
writer.WriteString(Value);
}
#endregion
}
请注意,此实现通过编写 xsi:nil="true" 正确捕获了 Value 属性的空值,但是如果 AttributeValue为 null 而 AttributeName 为非空,AttributeValue 将在反序列化时转换为空字符串。
