c# - Read then write html to xml file using linq xml and xml writer -
i reading value
of element <content>text <br /> break</content>
string , showing string in textbox
. afterwards user can modify possibly additional html tags. upon using linq query exact node insert user-input spiky bracket <> html tags normalized <br />
. how preseve html tags?
i read , tried solutions these questions failed apply use case: c# xml avoid html encode using xdocument
get html tags embedded in xml using linq
keep html tags in xml using linq xml
this example of xml file:
<events> <event id="0"> <content><br/></content> </event> </events>
how load , query:
xdocument xml; xmltextreader xtr = new xmltextreader(this.pathxml); xtr.normalization = false; xml = xdocument.load(xtr, loadoptions.preservewhitespace); xtr.close(); var nodetoedit = xml.descendants("event").where(x => (string)x.attribute("id") == "0");
how manipulate xml file user input:
string userinput = "text <br /> break"; // read textbox control inside form foreach (var item in nodetoedit.elements()) { if(item.name == "content") { item.value = userinput; } }
how save:
changesaveindent(xml, this.pathxml); public static void changesaveindent(xdocument x, string path) { xmlwritersettings settings = new xmlwritersettings(); settings.indent = true; // indent tab. can changed " " or similar settings.indentchars = "\t"; using (xmlwriter writer = xmltextwriter.create(path, settings)) { x.save(writer); } }
my expected xml output file should this:
<events> <event id="0"> <content>text <br /> break</content> </event> </events>
sorry long post..
replace this:
if(item.name == "content") { item.value = userinput; }
with this:
if(item.name == "content") { item.replacewith(xelement.parse("<content>" + userinput + "</content>")); }
just note user input have valid xml work. if not, you'd best off breaking out call xelement.parse try catch block or adding input unescaped cdata, so:
if (item.name == "content") { item.value = ""; item.add(new xcdata(userinput)); }
which produce xml looks this:
... <content><![cdata[text <br /> break]]></content> ...
Comments
Post a Comment