1

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.

3
  • 1
    XML cannot have an array at the root level unless it is "Not Well Formed". Serialization requires a "Well Formed XML" so an array cannot be at the root. So you need another class calling credit if you want credit to be an array. The in the new class have public Credit[] credit { get;set;} Commented Feb 27, 2020 at 10:37
  • 1
    @jdweng I'm hoping (perhaps beyond hope) that those are simply two different unrelated examples, to illustrate what changes between scenarios Commented Feb 27, 2020 at 10:41
  • I understand thank you :) Commented Feb 27, 2020 at 15:25

1 Answer 1

3

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");
    }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the response , I consume an external API that requires XML like that, I really can't understand why too. can you please show me an example of how I can do that with XmlWriter :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.