PDA

View Full Version : [C#]convertire stringa in xml


RaouL_BennetH
10-12-2011, 00:11
Ciao a tutti. Ho una stringa così composta:



string strToXml = string.empty;

......

strToXml = "<caption='" + myCaption + "' >";

for(int i = 0; i < blah; i++)
{
strToXml += "<set name='" +myName + "' value='" + myValue + "' />"
}
strToXml += "</caption>";



Devo passare questa stringa in modo che arrivi formattata come se fosse il contenuto di un file xml.

Mi date una mano ?

Grazie :)

RaouL.

Kralizek
10-12-2011, 11:59
Premesso che il tuo codice non genera XML valido, io userei Linq to XML.

Qualcosa tipo

XElement element = new XElement("caption",
new XAttribute("unNome", myCaption),
from item in blah
select new XElement("set", new xattribute("name", item.name), new XAttribute("value", item.value)));
String xml = element.ToString();


Non scriverò mai più un code snippet dall'ipad!!!

gugoXX
12-12-2011, 12:55
In questo caso anche io procederei con Linq2XML.

Ma per casi piu' complessi o standard propenderei per lasciare fare il lavoro al framework mediante XML serialization.
Usando gli opportuni Attrbuti C# si puo' ottenere quasi quello che si vuole, purche' appunto standard.


class Program
{
static void Main(string[] args)
{
var cc = new ContainerClass
{
MyCaption = "This is my caption",
Sets = new[]
{
new Set {Name = "Name of the first set", Value = "Value of the first set"},
new Set {Name = "Name of the second set", Value = "Value of the second set"},
new Set {Name = "Name of the third set", Value = "Value of the third set"}
}
};


var serializer = new XmlSerializer(typeof(ContainerClass));

var sw=new StringWriter();
serializer.Serialize(sw, cc);
var str = sw.ToString();

Console.WriteLine(str);
Console.ReadKey();
}
}

[XmlRoot("rootName")]
public class ContainerClass
{
[XmlAttribute("caption")]
public string MyCaption;

[XmlArray("sets")]
[XmlArrayItem("set")]
public Set[] Sets;
}

public class Set
{
[XmlAttribute("name")]
public string Name;

[XmlAttribute("value")]
public string Value;
}



<?xml version="1.0" encoding="utf-16"?>
<rootName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" mlns:xsd="http://www.w3.org/2001/XMLSchema" caption="This is my caption">
<sets>
<set name="Name of the first set" value="Value of the first set" />
<set name="Name of the second set" value="Value of the second set" />
<set name="Name of the third set" value="Value of the third set" />
</sets>
</rootName>

Kralizek
12-12-2011, 13:06
minchia l'xml serializer... me l'ero proprio dimenticato :O

gugoXX
12-12-2011, 13:20
Gia'. Comodo se si ha a che fare sia con output ma magari anche con input.

Lo stesso pezzo di codice e' in grado di parsare il file XML e restituire le istanze delle classi gia' riempite (deserializzazione)

Kralizek
12-12-2011, 13:49
cmq voglio un editor di codice per ipad... scrivere quello snippet é stato un parto...