I generated a Class with a XML Schema (.xsd) using the Visual Studio xsd tool. Now I have the class and I want to output that object back into XML as defined by my xsd. I am wondering how to do that.
Thank you!
You need an XmlSerializer to take care of serializing your class:
using System.Text; // needed to specify output file encoding
using System.Xml;
using System.Xml.Serialization; // XmlSerializer lives here
// instance of your generated class
YourClass c = new YourClass();
// wrap XmlTextWriter into a using block because it supports IDisposable
using (XmlTextWriter tw = new XmlTextWriter(#"C:\MyClass.xml", Encoding.UTF8))
{
// create an XmlSerializer for your class type
XmlSerializer xs = new XmlSerializer(typeof(YourClass));
xs.Serialize(tw, c);
}
Related
Using C#, I can easily serialize a class instance to an XML:
XmlSerializer xsSubmit = new XmlSerializer(typeof(Parking));
using (StringWriter sww = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings { Indent = true }))
{
xsSubmit.Serialize(writer, myParking);
var xml = sww.ToString();
File.WriteAllText("myParking.xml", xml);
}
I can also create an XSD file for this class, using XSD.exe.
It is indeed possible to inline an XSD in an XML file (ref. https://msdn.microsoft.com/en-us/library/ms759142(v=vs.85).aspx)
How can I get, in C#, my instance as an XML having its XSD definition inlined in it?
I was trying to write an automatic method that retrieve a value from an XML file.
as i wrote the following code:
XmlDocument xDoc = new XmlDocument();
I found out that when I'm trying to access xDoc object while typing xDoc. , it does nothing, means no option to manipulate the object...
my usings are:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Office.Interop;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Xml;
using System.Collections.Generic;
Any ideas ?
Sounds like you need to make a class to put the XMLDocument in if (per your comment) that is the next line you could have attached.
What I mean is, as Jon Skeet said, are you sure Adam that you're not declaring the XMLDocument inside of the namespace instead of inside of a class. Should be something like:
using System.Xml;
namespace SomeNameSpace
{
public class MyClass
{
XMLDocument xDoc = new XMLDocument();
public void MyMethod() {
xDoc.DocumentType;
}
}
}
I'm trying to validate a serialized WCF Proxy class using an Xsd.
I've noticed that the generated Xml, isn't including the namespace on the parent element, but child elements have it. This means my validation throws could not find schema information for the element type errors.
If I manually add a default namespace, then the schema validation works.
My question is, if the request object has a serialization attribute for the namespace, why isn't that being generated automatically?
This is how I generate the serialized Xml for the proxy:
var path = #"C:\DataRequest.xml";
var data = new DataRequest();
using (var fileWriter = new StreamWriter(path))
{
var serializer = new XmlSerializer(data.GetType());
serializer.Serialize(fileWriter, data);
fileWriter.Close();
}
This produces the following DataRequest.xml:
<DataRequest>
<Data xmlns="urn:some:name:space">
<Id>1</Id>
</Data>
</DataRequest>
Here's my request object with the namespace serialization attribute:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.17929")]
<other attributes I snipped>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:some:name:space")]
public partial class DataRequest : object, System.ComponentModel.INotifyPropertyChanged {
I found that when using the XmlSerializer, to get the namespace at the root, one needs to apply the XmlRootAttribute to the target class.
I fixed the issue by dynamically getting the Namespace value when serializing.
Here's the modified function:
var dataType = data.GetType();
var xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(dataType, typeof(XmlTypeAttribute));
XNamespace ns = xmlAttribute.Namespace;
using (var fileWriter = new StreamWriter(filePath))
{
var xSerializer = new XmlSerializer(dataType, ns.NamespaceName);
xSerializer.Serialize(fileWriter, data);
fileWriter.Close();
}
The code came from this SO answer:
How can I dynamically read a classes XmlTypeAttribute to get the Namespace?
I've generated a HTML file and the top html declaration looks like this:
<html xml:lang="de-CH" lang="de-CH" xmlns="http://www.w3.org/1999/xhtml">
And then I try to convert it into a different format with this .Net 4 code:
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("Html_to_Sql.xslt");
fsHtmlXml = new FileStream(file.Name, FileMode.Create);
html = XmlReader.Create(file.FullName, settings);
proc.Transform(html, null, fsHtmlXml);
Unfortunately nothing happens as long as I have the xml, lang and xmlns attributes in the HTML.
Why is that?
Your XSLT will need to refer to elements in the http://www.w3.org/1999/xhtml namespace. You haven't posted your XSLT code yet, the the problem most likely lies in that file.
Will this work via XML and XPath
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
public class TransformXML
{
//This will transform xml document using xslt and produce result xml document
//and display it
public static void Main(string[] args)
{
try
{
XPathDocument myXPathDocument = new XPathDocument(sourceDoc);
XslTransform myXslTransform = new XslTransform();
XmlTextWriter writer = new XmlTextWriter(resultDoc, null);
myXslTransform.Load(xsltDoc);
myXslTransform.Transform(myXPathDocument, null, writer);
writer.Close();
StreamReader stream = new StreamReader (resultDoc);
Console.Write("**This is result document**\n\n");
Console.Write(stream.ReadToEnd());
}
catch (Exception e)
{
Console.WriteLine ("Exception: {0}", e.ToString());
}
}
}
The xmlns attribute specifies the namespace of the XML document. This works in much the same way as namespaces within C#, where two classes with the same name but different namespaces are considered to be completely different classes. Changing the XML namespaces means that your XSLT templates / XPath will not match.
I have tried to serialize data using XmlSerializer. I have found very a useful post: XML Serializable Generic Dictionary.
But in fact I need to put the result of serialization not in file but in a string variable, how can I do this?
Instead of using some StreamWriter which points to file you can use StringWriter class.
using (StringWriter writer = new StringWriter())
{
XmlSerializer serializer = new XmlSerializer(typeof (YourType));
serializer.Serialize(writer, yourObject);
}
XmlWriter.Create() function has one overload which takes StringBuilder, try using it.