简体   繁体   中英

XML Serialization different elementName for same object

I have the following Model in ASP.Net Core

[Serializable]
    [XmlRoot(ElementName = "CREDIT")]
    public class Credit
    {
  [XmlElement(ElementName = "D_numbern")]
        public string Number get; set; }
}

I did the serialization with StringWriter, the problem I should get XML like that

<CREDITS>
    <CREDIT ID="1">
     <D_number1>06</D_number1>
      </CREDIT>

      <CREDIT ID="2">
     <D_number2>06</D_number2>
      </CREDIT>
</CREDITS>

I didn't find a solution how to make n dynamic for each credit . thanks in advance for any assistance.

What you're after isn't something that XmlSerializer supports, and frankly it is a bad design for xml generally; not only is it redundant (xml is ordered: there's no need to tell it that you're item 1/2/3), but it is actively hostile to most xml tooling, including serializers, schema validators, etc.

My strong suggestion is to rethink the xml you want, or challenge the requirements if it isn't your idea. If the D_number42 will always match the ID="42" that is the parent, frankly the suffix serves absolutely no purpose. If it is a different number that only looks the same in these examples by coincidence, then: <D_number someattribute="42">06</D_number>

But if you must do this, you'll have to do it manually, via XDocument , XmlDocument , or XmlWriter .


as an example using XmlWriter :

    static void WriteCredit(XmlWriter xml, string id, string number)
    {
        xml.WriteStartElement("CREDITS");
        xml.WriteStartElement("CREDIT");
        xml.WriteAttributeString("ID", id);
        xml.WriteElementString("D_number" + id, number);
        xml.WriteEndElement();
        xml.WriteEndElement();
    }

usage that writes to the console:

    using (var xml = XmlWriter.Create(Console.Out))
    {
        WriteCredit(xml, "1", "06");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM