1

We've a problem with an XMl file from a application (not own written). The XML data is:

<?xml version="1.0"?>
<content>
    <data timestamp="1477118232031">
        <item0 attr1="0" attr2="TA" attr3="true" attr4="350.87" />
        <item1 attr1="0" attr2="TA" attr3="true" attr4="350.87" />
        <item2 attr1="0" attr2="TA" attr3="true" attr4="350.87" />
        <!-- ... -->
        <itemNN attr1="0" attr2="TA" attr3="true" attr4="350.87" />
    </data>
<content>

Is it possible to deserialze item0 - itemNN in an array (or list) in the data class ?

public class data {
    [XmlElement("itemNN?")] // here is the problem
    public List<item> Items { get; set; }

    [XmlAttribute("timestamp")]
    public int timestamp;
}

public class item {
    [XmlAttribute("attr1")]
    public string attr1 { get; set; }
    //....
}

The XML file has many more elements with the same problem.

raiserle
  • 677
  • 8
  • 31
  • 1
    This cannot be done with attributes. – Alexander Petrov May 30 '18 at 13:11
  • 1
    See [this](https://stackoverflow.com/q/37255149/5045688). – Alexander Petrov May 30 '18 at 13:13
  • You can't use xml attribue to achieve this. Another solution if to implement IXmlSerializable => https://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=vs.110).aspx – CodeNotFound May 30 '18 at 13:15
  • If you don't like implement the interface so another solution is to use Linq To Xml and construct the object without deserialization. – CodeNotFound May 30 '18 at 13:17
  • Thank you all for this hints. Another idee is: Open the XML as text file and replace item0 - itemNN with RegEx ( \ Item ). From your point of view, is this an adequate solution? – raiserle May 30 '18 at 13:37
  • Related or duplicate: [How to serialize an array to XML with dynamic tag names](https://stackoverflow.com/q/50415653/3744182) and [How do you deserialize XML with dynamic element names?](https://stackoverflow.com/q/37255149/3744182). – dbc May 31 '18 at 00:17
  • @AlexanderPetrov: I do not want to parse the XML file from a supplier myself. And I do not want to write more code than really necessary. The XML file has many more elements - all with the same problem .... And my boss says: There the supplier has to rework, for a simple interface implementation + schema file. Thank you all for help. – raiserle May 31 '18 at 06:42

0 Answers0