c# - Two xml declaration in single xml file error -


my requirement create xml file , add xml elements existing xml file.

first tried creating new xml file following code.

using (xmlwriter xmlwriter = xmlwriter.create(fstream, xmlsettings)) {     xmlwriter.writestartdocument(true);     xmlwriter.writestartelement("friends");     xmlwriter.writestartelement("friend");     xmlwriter.writeelementstring("name", "safiq");     xmlwriter.writeelementstring("like", "char");     xmlwriter.writeelementstring("unlike", "anger");     xmlwriter.writeelementstring("nickname", "good");     xmlwriter.writeelementstring("gift", "c#");     xmlwriter.writeendelement();     xmlwriter.writeendelement();     xmlwriter.writeenddocument();     xmlwriter.flush(); } 

next tried adding new elements existing file.

xdocument xdoc = xdocument.load(fstream); xelement x = new xelement("friend"); x.add(new xelement("name", "safiq")); x.add(new xelement("like", "char")); x.add(new xelement("unlike", "anger")); x.add(new xelement("nickname", "good")); x.add(new xelement("gift", "c#")); xdoc.descendants("friends").single().add(x); xdoc.save(fstream); 

but getting following output.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <friends>     <friend>         <name>safiq</name>         <like>char</like>         <unlike>anger</unlike>         <nickname>good</nickname>         <gift>c#</gift>     </friend> </friends> <?xml version="1.0" encoding="utf-8" standalone="yes"?> <friends>     <friend>         <name>safiq</name>         <like>char</like>         <unlike>anger</unlike>         <nickname>good</nickname>         <gift>c#</gift>     </friend>     <friend>         <name>safiq</name>         <like>char</like>         <unlike>anger</unlike>         <nickname>good</nickname>         <gift>c#</gift>     </friend> </friends> 

where going wrong?

you're using same stream load , save. after loading, stream positioned @ end of file... when save file afterwards, you're saving position.

i suggest have using statement load document , close file, using statement save file:

xdocument doc; using (var stream = ...) {     doc = xdocument.load(stream); } // manipulate doc using (var stream = ...) {     doc.save(stream); } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -