Convert an object to an XML string
Here are conversion method for both ways.
this = instance of your class
public string ToXML()
{
using(var stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stringwriter, this);
return stringwriter.ToString();
}
}
public static YourClass LoadFromXMLString(string xmlText)
{
using(var stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
}
Convert Java object to XML string
You can use the Marshaler's method for marshaling which takes a Writer as parameter:
marshal(Object,Writer)
and pass it an Implementation which can build a String object
Direct Known Subclasses:
BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
Call its toString method to get the actual String value.
So doing:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
Convert a list of objects to an xml string
I made a fiddle here that illustrates a way to serialize your object all at once, instead of piecing strings together.
I suspect your extra <Tweet></Tweet>
is because of a null or empty value in the list, because I am not experiencing it in my test above.
XmlSerializer Convert C# object to xml string
You cannot serialize class from your question using standard serialization tools so that it will have <book>
entries on the same level as <bookNum>
node.
When class saved with standard serialization tools list of your <book>
nodes will always be nested into separate array node that will be on the same level as <bookNum>
node. Same concerns records
array field on book
class.
To generate XML output that you want to - with <book>
nodes on same level as <bookNum>
node - you will have to implement IXmlSerializable interface in your books
class for custom serialization. To see examples of IXmlSerializable
implementation visit these links: StackOverflow answer, CodeProject article.
Another solution will be - as stated user Alexandr in comment to my answer - to inherit your books
class from List<book>
type and to have on your book
class field records
of class type that is inherited from List<record>
type.
When serializing class from your question, assuming that your assigned proper XmlRoot, XmlElement, XmlArray and XmlArrayItem attributes as follows:
[XmlRoot("books")]
public class books
{
[XmlElement("bookNum")]
public int bookNum { get; set; }
[XmlRoot("book")]
public class book
{
[XmlElement("name")]
public string name { get; set; }
[XmlRoot("record")]
public class record
{
[XmlElement("borrowDate")]
public string borrowDate { get; set; }
[XmlElement("returnDate")]
public string returnDate { get; set; }
}
[XmlArray("borrowRecords")]
[XmlArrayItem("record")]
public record[] records { get; set; }
}
[XmlArray("booksList")]
[XmlArrayItem("book")]
public book[] books { get; set; }
}
you will get XML output as follows:
<books>
<bookNum>2</bookNum>
<booksList>
<book>
<name>Book 1</name>
<borrowRecords>
<record>
<borrowDate>2013-1-3</borrowDate>
<returnDate>2013-1-5</returnDate>
</record>
<record>
<borrowDate>2013-2-3</borrowDate>
<returnDate>2013-4-5</returnDate>
</record>
</borrowRecords>
</book>
<book>
<name>Book 2</name>
<borrowRecords>
<record>
<borrowDate>2013-1-3</borrowDate>
<returnDate>2013-1-5</returnDate>
</record>
<record>
<borrowDate>2013-2-3</borrowDate>
<returnDate>2013-4-5</returnDate>
</record>
</borrowRecords>
</book>
</booksList>
</books>
how to convert xml document object to string?
You will need to serialize your xmlDoc
back to XML once you have made the changes:
var s = new XMLSerializer();
var newXmlStr = s.serializeToString(xmlDoc);
Now you can do what you need to do with the string of updated XML, overwrite your xml
variable, or send it to the server, or whatever...
See the MDN docs for further info
c# How to convert Object to XML
var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(YourData));
serializer.Serialize(writer, obj);
string xml = writer.ToString();
See also MSDN
Convert XML String to Object
You need to use the xsd.exe
tool which gets installed with the Windows SDK into a directory something similar to:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
And on 64-bit computers:
C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin
And on Windows 10 computers:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
On the first run, you use xsd.exe
and you convert your sample XML into a XSD file (XML schema file):
xsd yourfile.xml
This gives you yourfile.xsd
, which in a second step, you can convert again using xsd.exe
into a C# class:
xsd yourfile.xsd /c
This should give you a file yourfile.cs
which will contain a C# class that you can use to deserialize the XML file you're getting - something like:
XmlSerializer serializer = new XmlSerializer(typeof(msg));
msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));
Should work pretty well for most cases.
Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:
XmlSerializer serializer = new XmlSerializer(typeof(msg));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (msg)serializer.Deserialize(memStream);
or use a StringReader:
XmlSerializer serializer = new XmlSerializer(typeof(msg));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (msg)serializer.Deserialize(rdr);
Related Topics
Visual Studio 2013 Doesn't Discover Unit Tests
Argumentoutofrangeexception on Initialized List
Mvvm: Binding to Model While Keeping Model in Sync with a Server Version
Casting Object to Int Throws Invalidcastexception in C#
Ef Data Context - Async/Await & Multithreading
Convert Transparent Png to Jpg with Non-Black Background Color
Inheriting Comments from an Interface in an Implementing Class
How to Split a String into Multiple Values
Uploading and Downloading Large Files in ASP.NET Core 3.1
Complex Models and Partial Views - Model Binding Issue in ASP.NET MVC 3
Dbset.Attach(Entity) VS Dbcontext.Entry(Entity).State = Entitystate.Modified
How to Convert a Class into Dictionary<String,String>
Getting Current Directory in .Net Web Application
How to Get a List<String> Collection of Values from App.Config in Wpf