0

actually I'm trying to serialize an XMl file in C# and it's working good for elements but not for attributes I get the attributes as an XML elements I've tried so many things : xmlAttribute, xmlAttribute with XmlRoot..... but it's not working

here is an exemple of how I do it

 public class Book
 {
  [XmlAttribute("id")]
  public string id {get;set;}
 }

what I want :

<Book id="1"></Book >

what I got :

<Book>
   <id>1</id>
</Book>

Thank you

sr9419
  • 25
  • 6

1 Answers1

0

Using XmlSerializer, I got the desired result

var book = new Book() { id = "1"};

using (var stringwriter = new System.IO.StringWriter())
{
    var serializer = new XmlSerializer(book.GetType());
    serializer.Serialize(stringwriter, book);
    Console.WriteLine(stringwriter.ToString());
}

Output

<?xml version="1.0" encoding="utf-16"?>
<Book id="1" />
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25
  • thnx for your respond , in fact what I want is to get the data directly from an xml file (I just give an exemple) so I'm using XmlSerializer but I don't wanna set the value of Id , it has to be taken directly from the file...all but the attributs works for me – sr9419 Feb 04 '20 at 16:03
  • confused. can you please paste the code which you tried – Krishna Varma Feb 04 '20 at 16:06