Question

I want to make an xml file (using c# with XmlWriter) and I need to have 2 or more Elements with different attribute Values. for example:

<MyGuest Type = "Adult" Number = "2">
<MyGuest Type = "Child" Number = "1" Age = "12">

is this something that can be done with XmlWriter? when I use

 writer.WriteAttributeString("Number","2");
    writer.WriteAttributeString("Type","Aduld");


    writer.WriteAttributeString("Age","12");
    writer.WriteAttributeString("Number","1");
    writer.WriteAttributeString("Type","Child");

I get en exception that says "Additional information: 'Number' is a duplicate attribute name."

Any advice please?

So it seems that the question is asked wrongly. I want to add different values to that attributes in the xml file so it would look like this:

<Guests>
   <MyGuest Type = "Adult" Number = "2">
   <MyGuest Type = "Child" Number = "1" Age = "12">
</Guests>

any advice please?

Thank you for your time!

Was it helpful?

Solution

I think something like this is what you want:

writer.WriteStartElement("MyGuest");
writer.WriteAttributeString("Type","Adult");
writer.WriteAttributeString("Number","2");
writer.WriteEndElement();

writer.WriteStartElement("MyGuest");
writer.WriteAttributeString("Type","Child");
writer.WriteAttributeString("Age","12");
writer.WriteAttributeString("Number","2");
writer.WriteEndElement();

But generally it would be better to know more about your usecase. Are Child and Adult classes you want to serialize? Then I would propose you that the classes should implement IXmlSerializable. This forces the types to implement Read and WriteXml methods. In these methods you can put the logic and call them from outside. This gives you more loose coupling and also more flexibillity if you add new types. Then you dont have to change your "one-method-serialization" every time. You would only implement the new behaviour in the new class it belongs.

If you go this way, you could make also a abstract base class "Guest" that has the property "Number". In the base Read and WriteXml you would de/serialize just this property and you dont have to repeat yourself in every additional "guest type" like child or adult...

OTHER TIPS

You can't do that: An attribute name cannot be used more than once in the same element. Whatever way you use to accomplish your goal - the result is not valid XML.

Well-formed XML cannot contain duplicate attributes on an element.

From the xml spec section 3.1:

Well-formedness constraint: Unique Att Spec

An attribute name MUST NOT appear more than once in the same start-tag or empty-element tag.

http://www.w3.org/TR/REC-xml/#sec-logical-struct

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top