Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I use this code -
C#
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" " );
settings.CloseOutput = true;
settings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create("books.xml" , settings))
    {
    writer.WriteStartElement( "book" );
    writer.WriteElementString( "title" , book.Title);
    writer.WriteElementString( "author" , book.Author.Name);
    writer.WriteElementString( "publisher" , book.Publisher);
    writer.WriteElementString( "price" , book.Price.ToString());
    writer.WriteEndElement();
    writer.Flush();
    }

output in books.xml is

<book>
.....
........
</book>


but I wanna output

<book key="A">
....
...
...
</book>


Just this. nothing else.

How to do this?

[edit]Code blocks added, HTML encoded - OriginalGriff[/edit]
Posted
Updated 6-Oct-13 5:09am
v2
Comments
Andreas Gieriet 6-Oct-13 16:45pm    
See Writing Attributes.
Cheers
Andi

Well, like most computer programs it will only do what it is coded to do. If you want to add an attribute to an element then you need to add the code at the appropriate point. If you don't want the other elements in the file then don't write them. The documentation[^] shows all the appropriate method details.
 
Share this answer
 
Assuming you want to add an attribute to the book element use the XmlWriter.WriteAttributeString Method (String, String)[^].

So add to your code:
C#
writer.WriteAttributeString( "key", "A" );
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900