c# - How can I write to the root element? -
when use following code can write xml file write outside root element.
streamwriter sw = file.appendtext(environment.currentdirectory + "\\settings.xml"); xmltextwriter xtw = new xmltextwriter(sw); xtw.writestartelement("connection"); xtw.writeelementstring("id", name); xtw.writeelementstring("version", "2.3.1"); xtw.writeelementstring("server", ip_textbox.text); xtw.writeelementstring("port", port_textbox.text); xtw.writeelementstring("uid", user_textbox.text); xtw.writeelementstring("password", pass_textbox.text); xtw.close();
after code runs xml looks this:
<?xml version='1.0' encoding='utf-8' ?> <root> </root> <connection><id>test</id><version>2.3.1</version><server>127.0.0.1</server><port>3306</port><uid>root</uid><password>root</password>
when should like:
<?xml version='1.0' encoding='utf-8' ?> <root> <connection> <id>test</id> <version>2.3.1</version> <server>127.0.0.1</server> <port>3306</port> <uid>root</uid> <password>root</password> </connection> </root>
again question how can write inside root element?
it looks file contains xml (likely <root></root>
based on sample output). since using appendtext
xml appended existing file instead of replacing. result nodes you've added outside of root , xml invalid.
there no reasonable way insert nodes text file (possible, hard).
if want generate complete xml xmlwriter need re-create file , add nodes starting root.
alternatively can load existing file xml (using xmldocument
or more popular xdocument
), add nodes "root" element , save whole file.
Comments
Post a Comment