c# - Adding XML nodes into an existing XML config file -
i have xml file contains node (in middle of xml file):
<stationssection> <stations /> </stationssection>
i need append becomes this:
<stationssection> <stations> <add comment="i'm here!" destinationfolderpath="c:\" ftphostname="ftp://upload.domain.com/" ftpfolderpath="myfolder/" ftpusername="555" ftppassword="secret!!!" ftptimeoutinseconds="20" /> <add comment="i'm here!" destinationfolderpath="c:\" ftphostname="ftp://upload.domain.com/" ftpfolderpath="myfolder/" ftpusername="555" ftppassword="secret!!!" ftptimeoutinseconds="20" /> </stations> </stationssection>
that data ("comment", "destinationfolderpath", etc.) stored in generic list of custom object - called "updatedstations". when try add them this:
foreach (var station in updatedstations) { xelement updatedstation = new xelement("add", elementtoadd); // "elementtoadd" has value xml.add(updatedstation); // "xml" xdocument }
...that "updatedstation" variable has value:
<add>comment="i'm here!" destinationfolderpath="c:\" ftphostname="myfolder/" ftpfolderpath="ftp://upload.domain.com/" ftpusername="555" ftppassword="secret!!!" ftptimeoutinseconds="20"</add>
when tries line:
xml.add(updatedstation);
i exception:
this operation create incorrectly structured document.
how can work?... thank you!
don't use string operations( updatedstation
). below example linq2xml + xpath (assuming can parts of updatedstation
)
var xdoc = xdocument.load(filename); var st = xdoc.xpathselectelement("//stationssection/stations"); st.add(new xelement( "add", new xattribute("comment","i'm here"), new xattribute("destinationfolderpath","c:\\") ) );
ps: don't forget include namespaces
using system.xml.xpath; using system.xml.linq;
Comments
Post a Comment