c# - How to create in memory XML document and get string out of it -


i create xml string special characters handling. turned out complicated , causing issues generating wrong xml. thinking build string using object system.xml , stringify() or string it. guess me special character cases.

//psudo code xmldoc doc = new xmldoc(); element ele= new element("xyz"); ele.value(oob.property) doc.appendnode(ele); ...  doc.getxmlstring(); 

can 1 please let me know how in c# .net2.0+ .

i find xmltextwriter more intuitive xmldocument editing.

e.g.:

string xmlstring = null; using(stringwriter sw = new stringwriter()) {     xmltextwriter writer = new xmltextwriter(sw);     writer.formatting = formatting.indented; // if want indented      writer.writestartdocument(); // <?xml version="1.0" encoding="utf-16"?>     writer.writestartelement("tag"); //<tag>      // <subtag>value</subtag>     writer.writestartelement("subtag");     writer.writestring("value");     writer.writeendelement();       // <subtag attr="hello">world</subtag>     writer.writestartelement("subtag");     writer.writestartattribute("attr");     writer.writestring("hello");     writer.writeendattribute();     writer.writestring("world");     writer.writeendelement();       writer.writeendelement(); //</tag>     writer.writeenddocument();      xmlstring = sw.tostring(); } 

after code xmlstring contain:

<?xml version="1.0" encoding="utf-16"?> <tag>   <subtag>value</subtag>   <subtag attr="hello">world</subtag> </tag> 

additional info:

using xmldocument be:


xmldocument doc = new xmldocument();  xmlnode tagnode = doc.createnode(xmlnodetype.element, "tag", null); doc.appendchild(tagnode);  xmlnode subtagnode1 = doc.createnode(xmlnodetype.element, "subtag", null); tagnode.appendchild(subtagnode1); xmltext subtagnode1value = doc.createtextnode("value"); subtagnode1.appendchild(subtagnode1value);   xmlnode subtagnode2 = doc.createnode(xmlnodetype.element, "subtag", null); tagnode.appendchild(subtagnode2); xmlattribute subtagnode2attribute = doc.createattribute("attr"); subtagnode2attribute.value = "hello";  subtagnode2.attributes.setnameditem(subtagnode2attribute); xmltext subtagnode2value = doc.createtextnode("world"); subtagnode2.appendchild(subtagnode2value);  string xmlstring = null; using(stringwriter wr = new stringwriter()) {     doc.save(wr);     xmlstring = wr.tostring(); } 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -