[C#] XML Read/Write/Append/Delete

Vediamo come creare con c# un file xml con nodi, attributi e testo in questo formato, con XmlDocument XmlTextWriter:

[code lang=”bash” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]<img />c:\test\img.png
bla bla bla

<img />c:\test\img.png
bla bla bla[/code]

bene… facile facile con l’XMLTextWriter:

[code lang=”csharp” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]XmlTextWriter xw = new XmlTextWriter(fileName, Encoding.UTF8);

xw.WriteStartDocument();

/* nodo principale */
xw.WriteStartElement("city");
xw.WriteAttributeString("name", "milano");
xw.WriteAttributeString("thumbs", "1");

/* sotto nodi */
xw.WriteStartElement("thumb");
/* attributi */
xw.WriteAttributeString("id", "1");
xw.WriteAttributeString("nid", "111");
xw.WriteAttributeString("t", "0");
xw.WriteStartElement("coord");
xw.WriteAttributeString("lat", "45");
xw.WriteAttributeString("lon", "12");
xw.WriteEndElement();
xw.WriteStartElement("pos");
xw.WriteAttributeString("b", "1.5");
xw.WriteAttributeString("t", "-0.5");
xw.WriteEndElement();

xw.WriteStartElement("img");
xw.WriteString("c:\test\img.png");
xw.WriteEndElement();

xw.WriteStartElement("desc");
xw.WriteString("bla bla bla");
xw.WriteEndElement();
xw.WriteEndElement();

/* chiusura tag */
xw.WriteEndElement();
xw.WriteEndDocument();
xw.Close();[/code]

Ok! Il nostro file XML è pronto!!! Ricordati di aggiungere le librerie per l’xml tipo System.Xml.

Invece, per fare l’append di un sottonodo al file xml principale bisogna utilizzare XmlDocument.

[code lang=”csharp” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]XmlDocument xd = new XmlDocument();
xd.Load(fName);/* con xpath punto al nodo interessato */
XmlAttribute tmpN = xd.SelectSingleNode("city//@thumbs") as XmlAttribute;//XmlNode lastId = (xd.LastChild).LastChild.SelectSingleNode("@id");/* prendo i sottonodi e aggiungo valori */
XmlElement thumbNode = xd.CreateElement("thumb");
XmlAttribute thumbId = xd.CreateAttribute("id");
thumbId.Value = "000";XmlAttribute thumbNId = xd.CreateAttribute("nid");
thumbNId.Value = Request["nid"];
XmlAttribute thumbT = xd.CreateAttribute("t");
thumbT.Value = Request["type"];

thumbNode.SetAttributeNode(thumbId);
thumbNode.SetAttributeNode(thumbNId);
thumbNode.SetAttributeNode(thumbT);

XmlElement coordElem = xd.CreateElement("coord");
XmlAttribute coordLat = xd.CreateAttribute("lat");
coordLat.Value = Request["lat"];

XmlAttribute coordLon = xd.CreateAttribute("lon");
coordLon.Value = Request["lon"];

coordElem.SetAttributeNode(coordLat);
coordElem.SetAttributeNode(coordLon);

XmlElement posElem = xd.CreateElement("pos");
XmlAttribute posB = xd.CreateAttribute("b");
posB.Value = "-4.3";

XmlAttribute posT = xd.CreateAttribute("t");
posT.Value = "123";

posElem.SetAttributeNode(posB);
posElem.SetAttributeNode(posT);

XmlElement imgElem = xd.CreateElement("img");
imgElem.InnerText = Request["img"];

XmlElement descElem = xd.CreateElement("desc");
descElem.InnerText = Request["et"];

thumbNode.AppendChild(coordElem);
thumbNode.AppendChild(posElem);
thumbNode.AppendChild(imgElem);
thumbNode.AppendChild(descElem);

xd.DocumentElement.InsertAfter(thumbNode, xd.DocumentElement.LastChild);

XmlNodeList xmlNL = xd.GetElementsByTagName("thumb");
tmpN.Value = xmlNL.Count.ToString();

FileStream fsxml = new FileStream(fName, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
xd.Save(fsxml);
fsxml.Close();[/code]

Meglio… adesso abbiamo aggiunto i sottonodi che ci interessano…
…ma ora? Ho sbagliato ad inserire un nodo, come si cancella???

Easy…
utilizziamo sempre XPATH perchè ci piace tanto!

[code lang=”csharp” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]/* apro, cerco e cancello */
XmlDocument d = new XmlDocument();
d.Load("xmlfile.xml");
XmlNode t = d.SelectSingleNode("city//thumb[@id=’" + idValue + "’]");
t.ParentNode.RemoveChild(t);/* salvo */
FileStream fsxml = new FileStream(local, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
d.Save(fsxml);
fsxml.Close();[/code]

oppure un delete / update del conteggio nodi ad esempio:

[code lang=”csharp” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]XmlDocument d = new XmlDocument();
d.Load("xmlfile.xml");
XmlNode t = d.SelectSingleNode("city//thumb[@id=’" + idValue + "’]");
t.ParentNode.RemoveChild(t);/* update valore del conteggio (esempio) */
XmlNodeList xmlNL = d.GetElementsByTagName("thumb");
int c = xmlNL.Count;
XmlAttribute tmpN = d.SelectSingleNode("city//@thumbs") as XmlAttribute;
tmpN.Value = c.ToString();FileStream fsxml = new FileStream(local, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
d.Save(fsxml);
fsxml.Close();[/code]

Un omaggio: MSDN

yep!

[ref -> albertopasca.it]

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.