I am trying to remove all nodes from an XML file. But it also removes the open tag with the open root node. Using C # anf Linq
Input data:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <root> <ErrData> <Count>1</Count> <Timestamp>2011-11-21T11:57:12.3539044-05:00</Timestamp> </ErrData> <ErrData>max of 20 ErrData elements</ErrData> </root>
Expected OP:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <root> </root>
Actual OP: EDITED
<?xml version="1.0" encoding="utf-8" standalone="no"?> <root />
Code:
XDocument docs = XDocument.Load(path); try { docs.Descendants("ErrData").Remove(); }
CODE:
Below is the code I'm using, the concept is the error count and timestamp are written to an XML file. After reaching the threshold value, e-mail will be sent by function and delete all nodes from xml. Then, when the following error occurs, it will begin to enter into the xml file, as shown below,
XDocument doc = null; XElement el; if (!System.IO.File.Exists(path)) { doc = new XDocument(new XDeclaration("1.0", "utf-8", "no")); el = new XElement("root"); //el = new XElement("root"); XComment comment = new XComment("Log the error count and error message"); doc.Add(comment); } else { doc = XDocument.Load(path); } XElement p1 = new XElement("ErrData"); XElement p1Count = new XElement("Count", eventCount); XElement p1Windowsatrt = new XElement("Timestamp", windowStart); p1.Add(p1Count ); p1.Add(p1Windowsatrt ); if (doc.Root != null) { el = doc.Root; el.Add(p1); } else { el = new XElement("root"); el.Add(p1); } try { doc.Add(el);//Line throwing the exeception } catch (Exception e) { } finally { doc.Save(path); }
source share