I have this XML file which have 3 Words.
<synset id="n00252662" type="n">
<lex_filenum>04</lex_filenum>
<word lex_id="1">purge</word>
<word lex_id="1">purging</word>
<word lex_id="1">purgation</word>
<pointer refs="n01247647">Hypernym</pointer>
<pointer refs="v00905283" source="3" target="1">Derivationally related form</pointer>
<pointer refs="v00475647" source="2" target="1">Derivationally related form</pointer>
<pointer refs="v00475819" source="1" target="2">Derivationally related form</pointer>
<pointer refs="v00905283" source="1" target="1">Derivationally related form</pointer>
<pointer refs="n00252894">Hyponym</pointer>
<def>the act of clearing yourself (or another) from some stigma or charge</def>
</synset>
And DictionaryList.cs
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml;
using UnityEngine;
using System.IO;
[XmlRoot("DictionaryList")]
public class DictionaryList
{
[XmlArray("synsets")]
[XmlArrayItem("synset")]
public List<Dictionary> Dict = new List<Dictionary>();
//string filepath = Application.dataPath + "/Resources/gamedata.xml";
public static DictionaryList Load(string path)
{
var serializer = new XmlSerializer(typeof(DictionaryList));
using (var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as DictionaryList;
}
}
//Loads the xml directly from the given string. Useful in combination with www.text.
public static DictionaryList LoadFromText(string text)
{
var serializer = new XmlSerializer(typeof(DictionaryList));
return serializer.Deserialize(new StringReader(text)) as DictionaryList;
}
}
Then The Dictionary.cs
using System.Xml;
using System.Xml.Serialization;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Dictionary
{
public string word;
public string def;
public string example;
public Dictionary()
{
}
public Dictionary(string nme, string Des)
{
word = nme;
def = Des;
}
}
In my Code, the deserializer does not Include the word purging and purgation since the word <- variable is not an Array.
I have tried to make it an array List but I am not sure if the the deserializer will even put the other words if I make an List array word to it.
Plus accessing the the List inside the list is giving me a problem. I want to know if there is an option I can take where I can access or even store the word as an array without altering the XML file.
And this is my main Dictionary file
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Linq;
using UnityEngine.UI;
public class MainDictionary : MonoBehaviour {
DictionaryList DictionaryCollectionNoun;
DictionaryList DictionaryCollectionVerb;
DictionaryList DictionaryCollectionADV;
public InputField SearchField;
public Text NameField;
public Text DetailsField;
public Text DebugText;
public Text ExampleField;
public TextAsset textAssetNoun;
public TextAsset textAssetVerb;
public TextAsset textAssetADV;
// Use this for initialization
void Start () {
//TextAsset textAsset = (TextAsset)Resources.Load("datanoun", typeof(TextAsset));
//XmlDocument xmldoc = new XmlDocument ();
//xmldoc.LoadXml ( textAsset.text );
DebugText.text = Application.dataPath;
textAssetNoun = (TextAsset)Resources.Load("datanoun");
textAssetVerb = (TextAsset)Resources.Load("dataverb");
textAssetADV = (TextAsset)Resources.Load("dataadv");
//XmlDocument xmldoc = new XmlDocument();
//xmldoc.LoadXml(textAsset.text);
//Example Psuedocode Danzee Mode;
//var xmlData = #"<DictionaryList><synsets><synset><word>test</word><def>Fun</def></synset></synsets></DictionaryList>";
DictionaryCollectionNoun = DictionaryList.LoadFromText(textAssetNoun.text);
DictionaryCollectionVerb = DictionaryList.LoadFromText(textAssetVerb.text);
DictionaryCollectionADV = DictionaryList.LoadFromText(textAssetADV.text);
//Debug.Log(Application.dataPath);
//DebugText.text = xmldoc.ToString();
}
public void ChangeSearch()
{
//Dictionary Result = new Dictionary("No Result", "No Description");
//bool nounBool = DictionaryCollectionNoun.Dict.Any(p => p.word == SearchField.text.ToLower()) ? true : false;
//bool verbBool = DictionaryCollectionVerb.Dict.Any(p => p.word == SearchField.text.ToLower()) ? true : false;
//bool advbool = DictionaryCollectionADV.Dict.Any(p => p.word == SearchField.text.ToLower()) ? true : false;
//if (nounBool)
//{
// Result = DictionaryCollectionNoun.Dict.Find(x => x.word == SearchField.text.ToLower());
//}
//else if (verbBool)
//{
// Result = DictionaryCollectionVerb.Dict.Find(x => x.word == SearchField.text.ToLower());
//}
//else if (advbool)
//{
// Result = DictionaryCollectionADV.Dict.Find(x => x.word == SearchField.text.ToLower());
//}
//NameField.text = Result.word1;
//DetailsField.text = Result.def2;
//ExampleField.text = Result.example;
}
}
Try the following:
public class Word
{
[XmlAttribute("lex_id")]
public string LexId { get; set; }
[XmlText]
public string Value { get; set; }
public override string ToString()
{
return Value;
}
public static explicit operator string(Word word)
{
if (word == null)
return null;
return word.Value;
}
}
public class SynsetPointer
{
[XmlAttribute("refs")]
public string Refs { get; set; }
[XmlAttribute("source")]
public string Source { get; set; }
[XmlAttribute("target")]
public string Target { get; set; }
[XmlText]
public string Value { get; set; }
}
[XmlRoot("synset")]
[XmlType("synset")]
public class Synset
{
public Synset()
{
this.Pointers = new List<SynsetPointer>();
this.Words = new List<Word>();
}
[XmlElement("lex_filenum")]
public int LexFilenum { get; set; }
[XmlElement("word")]
public List<Word> Words { get; set; }
[XmlIgnore]
public IEnumerable<string> WordValues { get { return (Words == null ? null : Words.Select(w => (string)w)); } }
[XmlElement("pointer")]
public List<SynsetPointer> Pointers { get; set; }
[XmlElement("def")]
public string Definition { get; set; }
}
[XmlRoot("DictionaryList")]
public class DictionaryList
{
public DictionaryList()
{
this.Dict = new List<Synset>();
}
[XmlArray("synsets")]
[XmlArrayItem("synset")]
public List<Synset> Dict { get; set; }
//string filepath = Application.dataPath + "/Resources/gamedata.xml";
public static DictionaryList Load(string path)
{
var serializer = new XmlSerializer(typeof(DictionaryList));
using (var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as DictionaryList;
}
}
//Loads the xml directly from the given string. Useful in combination with www.text.
public static DictionaryList LoadFromText(string text)
{
var serializer = new XmlSerializer(typeof(DictionaryList));
return serializer.Deserialize(new StringReader(text)) as DictionaryList;
}
}
I renamed your Dictionary class to Synset for clarity, since c# already has various dictionary classes which do something different.
To read multiple word elements into an array, declare it as a List<Word> in the Synset class, then apply the [XmlElement] attribute. This tells the serializer to expect repeated occurrences of the word element rather than a nested list of elements.
This will successfully read and write XML that looks like this:
<DictionaryList>
<synsets>
<synset>
<lex_filenum>4</lex_filenum>
<word lex_id="1">purge</word>
<word lex_id="1">purging</word>
<word lex_id="1">purgation</word>
<pointer refs="n01247647">Hypernym</pointer>
<pointer refs="v00905283" source="3" target="1">Derivationally related form</pointer>
<pointer refs="v00475647" source="2" target="1">Derivationally related form</pointer>
<pointer refs="v00475819" source="1" target="2">Derivationally related form</pointer>
<pointer refs="v00905283" source="1" target="1">Derivationally related form</pointer>
<pointer refs="n00252894">Hyponym</pointer>
<def>the act of clearing yourself (or another) from some stigma or charge</def>
</synset>
</synsets>
</DictionaryList>
Update
To loop through all the text values of all the Word classes in all the Synset classes in a DictionaryList, you can do:
var testXml = #"<DictionaryList> <synsets> <synset id=""n00001740"" type=""n""> <lex_filenum>03</lex_filenum> <word lex_id=""0"">entity</word> <pointer refs=""n00001930 n00002137 n04424418"">Hyponym</pointer> <def>that which is perceived or known or inferred to have its own distinct existence (living or nonliving)</def> </synset> </synsets> </DictionaryList>";
var dict = DictionaryList.LoadFromText(testXml);
foreach (var synSet in dict.Dict)
{
var words = synSet.WordValues.ToList();
var word0 = (words.Count > 0 ? words[0] : null);
var word2 = (words.Count > 2 ? words[2] : null);
// Do something with the words.
}
Update 2
To search for a Synset containing a given word, you can do:
var word = "entity";
var Results = dict.Dict.Where(s => s.WordValues.Any(w => w == word)); // Find all synsets containing the word "entity"
var Result = dict.Dict.FirstOrDefault(s => s.WordValues.Any(w => w == word)); // Find the first synsets containing the word "entity"
Related
I want to write a string into one Column in an .csv (Excel) file. My Problem is that the string is written into multiple Columns.
In this screenshot for example I have 20 Columns.
GetMetadataCompleteResponse resultValue = null;
string jsonData = null;
await Task.Run(() =>
{
byte[] rawData = Convert.FromBase64String(responseContent);
jsonData = CompressUtil.Unzip(rawData);
});
resultValue = JsonConvert.DeserializeObject<GetMetadataCompleteResponse>(jsonData);
foreach(string a in resultValue.Value.Values)
{
foreal += a;
}
await Log.Info("callWebservice for " + strUrl + ", Result: " + objErrorDetails.Code + ", " + foreal);
edit
I've noticed that the new Column starts after every ';'(semicolon). I probably can just replace it with something else.
I think you have 2 issues. The first one is how you write your CSV with simple string concatenation. With no escaping or double quote.
The Json will have commas , that will be separator in your CSV.
In order to produc e a valid CSV you should read the RFC 4180 and use a proper library to handle the Serialisation.
Here is an Minimal, Complete, and Verifiable example of writing a Json in a CSV column.
using CsvHelper;
using CsvHelper.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Program
{
public static void Main()
{
var input = new Foo
{
Label = "My Foo",
Bars = new List<Bar> {
new Bar{Label="Bar2"},
new Bar{Label="Bar1"},
new Bar{Label="Bar3"},
}
};
var json = JsonConvert.SerializeObject(input);
var myObject = new CsvObject
{
Label = "My CSV object",
FooString = json,
};
var result = "";
// Writing into a string instead of a file for debug purpuse.
using (var stream = new MemoryStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.RegisterClassMap<CsvObjectMap>();
csv.WriteHeader<CsvObject>();
csv.NextRecord();
csv.WriteRecord(myObject);
csv.NextRecord();
writer.Flush();
stream.Position = 0;
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}
private sealed class CsvObjectMap : ClassMap<CsvObject>
{
public CsvObjectMap()
{
Map( m => m.FooString );
Map( m => m.Label );
}
}
public class CsvObject
{
public string Label { get; set; }
public string FooString { get; set; }
}
public class Foo
{
public string Label { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string Label { get; set; }
}
}
Live demo : https://dotnetfiddle.net/SNqZX1
In this exemple I have used CsvHelper for CSV serialisation, and Json.NET for the Json serialisation. Note that Writing a CSV to a file is a more simlpe task that to a string like in this example
So I need to create a method that makes an XML file from a database, I have already written the stored procedures that get the information from a database for the XML now I only need to write the part where I convert my database to a XML file using the properties of another class that I have written as nodes.
public string CreateXML(Object YourClassObject){
XmlDocument xmlDoc =new XmlDocument(); //Represents an XML document,
// Initializes a new instance of the XmlDocument class.
XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());
// Creates a stream whose backing store is memory.
using (MemoryStream xmlStream =new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, YourClassObject);
xmlStream.Position = 0;
//Loads the XML document from the specified string.
xmlDoc.Load(xmlStream);
return xmlDoc.InnerXml;
}
}
This is some code I found online I think I can use for serializing my model, but i'm accessing the database over an event that I created (I'll provide the code tomorrow when I get to work). Anyway I'm accesing the database in the event like the following e.DataTable. Any ideas anybody?
My model looks like the following:
public class DataModel
{
string Sifra {get; set;}
public string Naziv {get; set;}
public string JM {get; set;}
public int Kolicina {get; set;}
public float Cena_x0020_vp {get; set;}
public float Cena_x0020_mp {get; set;}
public float Cena_x0020_bod {get; set;}
public string Slika {get; set;}
public string Grupa {get; set;}
}
This is a sample of how my generated XML should look like.
<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2019-04-17T19:13:54">
<row>
<Sifra>ADA110-100</Sifra>
<Naziv_x0020_artikla>Adapter 220/110VAC 100W</Naziv_x0020_artikla>
<JM>kom</JM>
<Kolicina>1</Kolicina>
<Cena_x0020_vp>2683.33</Cena_x0020_vp>
<Cena_x0020_mp>3220</Cena_x0020_mp>
<Cena_x0020_bod>28</Cena_x0020_bod>
<Slika1> ada110v.jpg</Slika1>
<Grupa>Adateri 110V AC</Grupa>
</row>
Problem solved:
private void CreateXML(DataTable dataTable)
{
var list = new List<Row>();
XmlSerializer writer = new XmlSerializer(typeof(List<Row>));
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ExportZaWeb.xml";
FileStream file = File.Create(path);
foreach (DataRow row in dataTable.Rows)
{
Row r = new Row();
r.Naziv = row["Naziv Artikla"].ToString();
r.JM = row["JM"].ToString();
r.Kolicina = row["Kolicina"].ToString();
r.Cena_x0020_vp = row["Cena vp"].ToString();
r.Cena_x0020_mp = row["Cena mp"].ToString();
r.Cena_x0020_bod = row["Cena bod"].ToString();
r.Slika = row["Slika1"].ToString();
r.Grupa = row["Grupa"].ToString();
list.Add(r);
}
writer.Serialize(file, list);
file.Close();
}
Why not let the stored procedure return the xml for you. The query in the stored procedure would lool something like this:
SELECT Sifra, Naziv, JM, Kolicina, Cena_x0020_vp, Cena_x0020_mp, Cena_x0020_bod, Slika, Grupa
FROM DataModel
FOR XML AUTO
Create a method which takes in a list or IEnumerable object of the Models and returns a string containing the XML (untested, but should get you started), this is assuming you already have the database data in usable objects:
public string GetXmlForModels(IEnumerable<DataModel> dataModels)
{
//Assume a list of DataModels is in dataModels of type IEnumerable<DataModel>
var doc = new XmlDocument();
foreach (var model in dataModels)
{
var row = (XmlElement)doc.AppendChild(doc.CreateElement("row"));
row.SetAttribute("xmlns:od", "urn:schemas-microsoft-com:officedat");
row.SetAttribute("generated", DateTime.Now.ToString("yy-MM-ddTHH:mm:ss"));
var sifraElement = doc.CreateElement("Sifra");
sifraElement.InnerText = model.Sifra;
row.AppendChild(sifraElement);
//Repeat top 3 lines for each element ...
doc.AppendChild(row);
}
return doc.OuterXml;
}
Use XML Serializer :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication110
{
class Program
{
const string INPUT_FILENAME = #"c:\temp\test.xml";
const string OUTPUT_FILENAME = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(INPUT_FILENAME);
string xml = reader.ToString();
XmlSerializer serializer = new XmlSerializer(typeof(DataRoot));
DataRoot root = (DataRoot)serializer.Deserialize(reader);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(OUTPUT_FILENAME,settings);
serializer.Serialize(writer, root);
}
}
[XmlRoot(ElementName = "dataroot", Namespace = "")]
public class DataRoot
{
[XmlElement(ElementName = "row", Namespace = "")]
public List<DataModel> rows { get; set; }
}
[XmlRoot(ElementName = "row", Namespace = "")]
public class DataModel
{
string Sifra { get; set; }
public string Naziv { get; set; }
public string JM { get; set; }
public int Kolicina { get; set; }
public float Cena_x0020_vp { get; set; }
public float Cena_x0020_mp { get; set; }
public float Cena_x0020_bod { get; set; }
public string Slika { get; set; }
public string Grupa { get; set; }
}
}
How to get a namespace set at a child level element when serializing an object to XML with C#?
The XML I want to end up with this as the XML output:
<clsPerson>
<FirstName>Jeff</FirstName>
<MI>J</MI>
<LastName>Jefferson</LastName>
<ns1:Addresses xmlns="www.whatever.co.uk">
<Home>Here</Home>
<Work>There</Work>
</Addresses>
</clsPerson>
The code I'm using is mostly taken from other questions, and is as follows:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
[XmlElement(Namespace = "www.whatever.co.uk")]
public clsPlaces Addresses;
public clsPerson()
{
clsPlaces clsPlaces = new clsPlaces();
}
}
[XmlRoot(Namespace = "")]
public class clsPlaces
{
public string Home { get; set; }
public string Work { get; set; }
}
class class1
{
static void Main(string[] args)
{
clsPerson p = new clsPerson();
var xml = "";
p.FirstName = "Jeff";
p.MI = "J";
p.LastName = "Jefefrson";
p.Addresses = new clsPlaces();
p.Addresses.Home = "Here";
p.Addresses.Work = "There";
var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(p.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
emptyNamepsaces.Add("ns", "www.whatever.co.uk");
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, p, emptyNamepsaces);
xml = stream.ToString();
}
Console.WriteLine(xml)
Console.ReadLine();
}
}
The above gives:
<clsPerson xmlns:ns="www.whatever.co.uk">
<FirstName>Jeff</FirstName>
<MI>J</MI>
<LastName>Jefefrson</LastName>
<ns:Addresses>
<Home>Here</Home>
<Work>There</Work>
</ns:Addresses>
How would I get the xmlns on the element only? I have tried everything I can see search stackoverflow, and not been able to find/understand the answer.
Thanks
Remove this - adding the namespace will ensure the prefix gets added to the root:
emptyNamepsaces.Add("ns", "www.whatever.co.uk");
The declaration for addresses will get added automatically. You also need to remove the empty namespace from clsPlaces, else the namspaces for Home and Work will be incorrect:
public class clsPlaces
{
public string Home { get; set; }
public string Work { get; set; }
}
The output will then look like this:
<clsPerson>
<FirstName>Jeff</FirstName>
<MI>J</MI>
<LastName>Jefefrson</LastName>
<Addresses xmlns="www.whatever.co.uk">
<Home>Here</Home>
<Work>There</Work>
</Addresses>
</clsPerson>
See this fiddle for a demo.
I have a situation where in I have to read my master data from XML files.
Hence I have created a Repository which looks like this.
public class XmlReadRepository<T> : IReadRepository<T> where T : class, new()
{
private IEnumerable<T> _data { get; set; }
private IQueryable<T> _query { get; set; }
public XmlReadRepository()
{
Type t = typeof(T);
//Load _data from xml
}
public IQueryable<T> All()
{
return _query;
}
public IQueryable<T> Get(System.Linq.Expressions.Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = "")
{
throw new NotImplementedException();
}
}
I have exported all my SQL database data into XML file using below SQL query
SELECT *
FROM Company
FOR XML RAW, ROOT('Company')
Whose outputs comes as below
<Company>
<row Id="1" Name="ABC" StartDate="2000-03-01" />
<row Id="2" Name="XYZ" StartDate="2001-13-11" />
</Company>
The xml is physically saved to a file and is embedded as a resource.
Now I am looking for some fast way to serialize the xml data into list.
I have tried loading the xml file with stream and then using reflection created objects by iterating through the XML. Is there any better way by which I can serialize the xml data to my C# object.
Also please share your inputs on whether is it good to have xml as an embedded resource as the size of each xml can be around 8MB and there are 5 such XMLs.
You can turn my code into a function
public class Row
{
private static XmlTextReader reader = null;
public int Id { get; set; }
public string name { get; set; }
public DateTime startDate { get; set; }
public Row() { }
public Row(TextReader sReader)
{
reader = new XmlTextReader(sReader); //can be filename instead of stringreader
}
public Row Get(string elementName)
{
Row results = null;
if (!reader.EOF)
{
if (reader.Name != elementName)
{
reader.ReadToFollowing(elementName);
}
if (!reader.EOF)
{
XElement newRow = (XElement)XElement.ReadFrom(reader);
results = new Row() { Id = (int)newRow.Attribute("Id"), name = (string)newRow.Attribute("Name"), startDate = (DateTime)newRow.Attribute("StartDate") };
}
}
return results;
}
}
Use xml linq like below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<Company>" +
"<row Id=\"1\" Name=\"ABC\" StartDate=\"2000-03-01\" />" +
"<row Id=\"2\" Name=\"XYZ\" StartDate=\"2001-13-11\" />" +
"</Company>";
XDocument doc = XDocument.Parse(xml); // use Load to read from file
var rows = doc.Descendants("row").Select(x => new
{
id = (int)x.Attribute("Id"),
name = (string)x.Attribute("Name"),
startDate = (DateTime)x.Attribute("StartDate")
}).ToList();
//using xmltextreader
List<Row> rows2 = new List<Row>();
StringReader sReader = new StringReader(xml);
XmlTextReader reader = new XmlTextReader(sReader); //can be filename instead of stringreader
while(!reader.EOF)
{
if (reader.Name != "row")
{
reader.ReadToFollowing("row");
}
if (!reader.EOF)
{
XElement newRow = (XElement)XElement.ReadFrom(reader);
rows2.Add(new Row() { Id = (int)newRow.Attribute("Id"), name = (string)newRow.Attribute("Name"), startDate = (DateTime)newRow.Attribute("StartDate") });
}
}
}
}
public class Row
{
public int Id { get; set; }
public string name { get; set; }
public DateTime startDate { get; set; }
}
}
I'm trying to generate xml output (based on a class) that looks like this:
<cdsXMLEnvelope>
<TestValue1>x1</TestValue1>
<inner>
<eTestValue1>e1</eTestValue1>
</inner>
<inner>
<eTestValue1>e1</eTestValue1>
</inner>
<inner>
<eTestValue1>e1</eTestValue1>
</inner>
</cdsXMLEnvelope>
[System.Xml.Serialization.XmlRootAttribute("cdsXMLEnvelope", Namespace = "", IsNullable = false)]
[XmlTypeAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
//public class cdsXMLEnvelope : cdsXMLinfo
public class cdsXMLEnvelope
{
[XmlElementAttribute(ElementName = "eTestValue1")]
public string eTestValue1 { get; set; }
[System.Xml.Serialization.XmlArrayItem("inner")]
public cdsXMLinfo[] cdsXMLinfo { get; set; }
}
//[XmlTypeAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public class cdsXMLinfo
{
[XmlElementAttribute(ElementName = "TestValue1")]
public string TestValue1 { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string TestValue3 { get; set; }
}
please help me hook this code up, change the class etc-- I keep trying a variety of ways & I get object not found & misc errors when trying to serialize it to xml
also can I avoid using an array for the inner elements? do I use lists?
I'll try to refine this question as we go, I know people hate these long ?'s
Thanks!!
{
cdsXMLEnvelope x = new cdsXMLEnvelope();
x.eTestValue1 = "x1";
x.cdsXMLinfo = new cdsXMLinfo[1];
x.cdsXMLinfo[0].TestValue1 = "xi1";
//x.cdsXMLinner[0].TestValue1 = "xi2";
XmlSerializer writer = new XmlSerializer(x.GetType());
StreamWriter file = new StreamWriter("x.xml");
writer.Serialize(file, x);
file.Close();
}
I think this gives what you want, however your example was not quite consistent:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Serialize
{
class Program
{
static void Main( string[] args )
{
var envelope = new CdsXmlEnvelope
{
TestValue1 = "x1",
InnerList = new List<CdsXmlInfo>
{
new CdsXmlInfo {TestValue1 = "e1"},
new CdsXmlInfo {TestValue1 = "e1"},
new CdsXmlInfo {TestValue1 = "e1"},
}
};
var ns = new XmlSerializerNamespaces();
ns.Add( string.Empty, string.Empty );
var serializer = new XmlSerializer( typeof( CdsXmlEnvelope ) );
using( var stream = new MemoryStream() )
{
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
var writer = XmlWriter.Create( stream, settings );
serializer.Serialize( writer, envelope, ns );
stream.Position = 0;
Console.WriteLine( new StreamReader( stream ).ReadToEnd() );
}
Console.ReadLine();
}
}
[XmlRoot( "cdsXMLEnvelope" )]
public class CdsXmlEnvelope
{
[XmlElement( "TestValue1" )]
public string TestValue1 { get; set; }
[XmlElement( "inner" )]
public List<CdsXmlInfo> InnerList { get; set; }
}
public class CdsXmlInfo
{
[XmlElement( "TestValue1" )]
public string TestValue1 { get; set; }
[XmlAttribute]
public string TestValue3 { get; set; }
}
}
giving output:
<cdsXMLEnvelope>
<TestValue1>x1</TestValue1>
<inner>
<TestValue1>e1</TestValue1>
</inner>
<inner>
<TestValue1>e1</TestValue1>
</inner>
<inner>
<TestValue1>e1</TestValue1>
</inner>
</cdsXMLEnvelope>
If you have the schema, you could try using Xsd.exe to generate the C# classes for you.