C # /. NET XML Serializer - using a property as an element name

Warning - I'm not an xml guru.

Here is what I have:

<Fields>
  <Field name="BusinessName" look-up="true">My Business</Field>
  <Field name="BusinessType" look-up="false">Nobody really knows!</Field>
</Fields>

This returns to the following:

[XmlArrayItem(ElementName = "Field")]
public List<UserInfoField> Fields;

and

[Serializable, XmlRoot("Field")]
public class UserInfoField
{
    [XmlAttributeAttribute("name")]
    public string Name;

    [XmlText]
    public string Value;

    [XmlAttributeAttribute("look-up")]
    public bool LookUp;
}

In any case, to get this serialized output:

<Fields>
  <BusinessName look-up="true">My Business</BusinessName>
  <BusinessType look-up="false">Nobody really knows!</BusinessType>
</Fields>

I understand that this can be too magical and can imagine that there is a good reason why this should not work ... but I believe that it is possible, and this is a good place to ask :)

+3
source share
2 answers

XmlSerializer (, , Framework) , . , , .

. node, , Name node. IXmlSerializable. , .

+3

[XmlArray], [XmlArrayItem] , http://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.71).aspx

[XmlArray("Fields")]
[XmlArrayItem("Field")]
public List<UserInfoField> Fields;

arroung :

<root>
  <Fields>
    <Field name="BusinessName" look-up="true">My Business</Field>
    <Field name="BusinessType" look-up="false">Nobody really knows!</Field>
  </Fields>
</root>

, :

[Serializable, XmlRoot("Root")]
public class Fields
{

    [XmlArray("Fields")]
    [XmlArrayItem(ElementName = "Field")]
    public List<UserInfoField> Fields;
}

[Serializable, XmlRoot("Field")]
public class UserInfoField
{
    [XmlAttributeAttribute("name")]
    public string Name;

    [XmlText]
    public string Value;

    [XmlAttributeAttribute("look-up")]
    public bool LookUp;
}
+2

Source: https://habr.com/ru/post/1730614/


All Articles