I have this code, how I can remove the namespace from output xml
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(OrderTable));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, null);
xs.Serialize(xmlTextWriter, ot);
string result = Encoding.Default.GetString(memoryStream.ToArray());
<?xml version="1.0" ?>
- <OrderTable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ForceUpdate>false</ForceUpdate>
<TableId xsi:nil="true" />
<UpdatedBy>Jack</UpdatedBy>
</OrderTable>
I want to remove xmlns, I googled, but those are not helping me.
I want to remove xmlns
All you have to do is using XmlSerializerNamespaces
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(xmlTextWriter, ot, ns);
Related
I have an xml file that is styled with xslt to produce html email template. I get values from users dynamically and replace xml elements text with the values received. How can i get that xml file and send as html email body in c#?
My Xml Looks Like This
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl" href="EmailTemplateStyleForHTML.xslt"?>
<EmailTemplate>
<subject>Information from xyz</subject>
<displayName>abcd</displayName>
<Message1>
Thanks you for registering to xyz.
</Message1>
<Copyright>Copyright xyz</Copyright>
</EmailTemplate>
I am using LINQ to set the values to the xml.
Note: I know how to get and set the values from xml but what i want is to grab the whole xml file in to the email body.
If you think there is a better approach for this i would love to hear that. I would really appreciate your help.
Edited after Reply:
The xsl transformation part :
TextReader tr1 = new StringReader(#"EMailTemplateHtml.xml");
var tr11 = new XmlTextReader(tr1);
var xPathDocument = new XPathDocument(tr11);
//read XSLT
TextReader tr2 = new StringReader(#"EmailTemplateStyleForHTML.xslt");
var tr22 = new XmlTextReader(tr2);
var xslt = new XslTransform();
xslt.Load(tr22);
var sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);
xslt.Transform(xPathDocument, null, tw);
emailBody = sb.ToString();
I am doing the transformation as you said(#Roy Ashbrook) am i missing anything here?
I believe you will need to actually perform the XSL transform in memory, not reference it in the XML itself. It's possible you could store the XSL in a remote location and reference it that way, but I wouldn't
so:
inject your values into your xml string
transform your xml using your xsl
make that your html message body
Here is some code. Mostly borrowed from/inspired by:
How to transform XML as a string w/o using files in .NET? and Sending E-mail using C#.
void Main()
{
SendHtmlBody(GetHtmlBody());
}
void SendHtmlBody(string HtmlBody){
using(SmtpClient c = new SmtpClient())
{
//set smtp options here
using(MailMessage msg = new MailMessage("from#replace.me","to#replace.me"))
{
msg.Subject = "Testing Bulk mail application";
msg.Body = HtmlBody;
msg.IsBodyHtml = true;
//c.Send(msg);
}
}
}
string GetHtmlBody(){
string xmlInput = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<EmailTemplate>
<subject>Information from xyz</subject>
<displayName>abcd</displayName>
<Message1>
Thanks you for registering to xyz.
</Message1>
<Copyright>Copyright xyz</Copyright>
</EmailTemplate>";
string xslInput = #"<?xml version=""1.0"" encoding=""ISO-8859-1""?>
<xsl:stylesheet version=""1.0""
xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:template match=""/"">
<html>
<body>
<h5><xsl:value-of select=""EmailTemplate/subject""/></h5>
<h5><xsl:value-of select=""EmailTemplate/displayName""/></h5>
</body>
</html>
</xsl:template>
</xsl:stylesheet>";
using (StringReader srt = new StringReader(xslInput)) // xslInput is a string that contains xsl
using (StringReader sri = new StringReader(xmlInput)) // xmlInput is a string that contains xml
{
using (XmlReader xrt = XmlReader.Create(srt))
using (XmlReader xri = XmlReader.Create(sri))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
using (StringWriter sw = new StringWriter())
using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
{
xslt.Transform(xri, xwo);
return sw.ToString();
}
}
}
}
I getting xml through web service in string format and to pass through xmlreader, I am converting the string to a stream object. But cannot figure out what I am missing. The xml and schema mentioned here is a sample.
class Program
{
static void Main(string[] args)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string leadxml = sw.ToString();
XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add(string.Empty,"books.xsd");
xmlSettings.ValidationType = ValidationType.Schema;
byte[] byteArray = Encoding.ASCII.GetBytes(leadxml);
MemoryStream stream = new MemoryStream(byteArray);
XmlReader reader = XmlReader.Create(stream, xmlSettings);
// Parse the file.
while (reader.Read());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
xml is:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0"/>
</bookstore>
xsd is:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="book">
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
First of all, if all your doing is getting the Xml into a string, this entire block of code is unnecessary:
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string leadxml = sw.ToString();
Instead just do:
string leadxml = File.ReadAllText("books.xml");
Secondly, if you have a string already, it is completely unnecessary to do all this conversion on the string. The XmlReader.Create method has a signature which accepts a TextReader. StringReader derives from TextReader. Therefore, this:
byte[] byteArray = Encoding.ASCII.GetBytes(leadxml);
MemoryStream stream = new MemoryStream(byteArray);
XmlReader reader = XmlReader.Create(stream, xmlSettings);
Can be replaced with this:
StringReader leadxmlStringReader = new StringReader(leadXml);
XmlReader reader = XmlReader.Create(leadxmlStringReader, xmlSettings);
For any further assistance with this question, you will need to provide Exception details and/or specific error messages.
StringWriter assumes a UTF-16 encoding by default, which means you'll get an XML declaration with UTF-16 in it. You're then using Encoding.ASCII to get a binary representation though, which is incompatible with the UTF-16 declaration.
To be honest, it's not really clear why you're doing this in the first place - there's almost certainly a better way of achieving your goal, but we can't really tell what your goal is, so we can't advise what that better way might be.
EDIT: For example, this might be what you're really after:
XmlReaderSettings xmlSettings = new XmlReaderSettings
{
Schemas = { { "", "books.xsd" } },
ValidationType = ValidationType.Schema
}
using (var reader = XmlReader.Create("books.xml", xmlSettings))
{
while (reader.Read()) {}
}
I'm using the XSLT found here to transform content in HTML to Markdown format but the results I'm getting are plain text without the Markdown formatting syntax. Here's the function I'm using:
private static string ConvertToText()
{
string text = string.Empty;
XmlDocument xsl = new XmlDocument();
xsl.CreateEntityReference("nbsp");
xsl.Load(System.Web.HttpContext.Current.Server.MapPath("/Test/markdown.xslt"));
XmlReader xr = XmlReader.Create(System.Web.HttpContext.Current.Server.MapPath("/Test/html.xml"));
//creating stringwriter
StringWriter writer = new System.IO.StringWriter();
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xsl);
xslt.Transform(xr, null, writer);
//return string
text = writer.ToString();
writer.Close();
return text;
}
Can anyone tell me why it's not working?
Thanks.
I guess your problem is the xmlns in your input XML. Try either to remove it in the xr variable before you transform it or to adjust your XSL file with namespace declarations like:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:html="http://www.w3.org/1999/xhtml">
...
<xsl:template match="html:h3">
...
I have successfully been able to transform a simple xml file with data to another xml file (excel template) using a xsl template, this is what my xsl file looks like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" standalone="yes"/>
<xsl:template match="/">
<xsl:processing-instruction name="mso-application">
<xsl:text>progid="Excel.Sheet"</xsl:text>
</xsl:processing-instruction>
...(stuff here)...
</xsl:template>
</xsl:stylesheet>
The resulting xml file is written out correctly BUT with the exception of including
<?xml version="1.0"?>
at the top of the file. How can I get it to appear at the top?
Currently my resulting xml file starts with:
<?mso-application progid="Excel.Sheet"?>
...(rest of file)...
But what I need it to do is:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
.(rest of file)...
I'm doing this transform through a windows form with the following code:
XPathDocument myXPathDoc = new XPathDocument(xmlfile);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(xslfile);
XmlTextWriter myWriter = new XmlTextWriter(xmlexcelfile, null);
myWriter.Formatting = Formatting.Indented;
myWriter.Namespaces = true;
myXslTrans.Transform(myXPathDoc, null, myWriter);
myWriter.Close();
I've tried playing around with the xsl:output standalone="yes/no", as well as omit-xml-declaration="no". I've also tried (in the C#) code adding myWriter.WriteStartDocument(); before transforming but that was not allowed. I have tried searching online for this as well and keep coming back to the standalone="yes" but that isn't working. Is there something I am missing here? Oh and in case you are wondering why I need to have the
<?xml version="1.0"?>
at the top of the resulting file, it's because when opening the xml file with excel, excel doesn't recognize it correctly but if it is included then excel opens it correctly...
You can do this
<xsl:output method="xml" indent="yes" omit-xml-declaration="no" />
or something similar to this using XmlWriterSettings
Edit: Added more code. Previous was missing some parts
XmlWriterSettings writerSettings = null;
XsltArgumentList transformationArguments = null;
XslCompiledTransform transformer = null;
MemoryStream memoryStream = null;
XPathDocument xPathDocument = null;
StringBuilder sb = null;
XmlWriter writer = null;
XmlDocument resultXml = null;
try
{
writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = false; // This does it
writerSettings.Indent = true;
transformationArguments = new XsltArgumentList();
transformer = new XslCompiledTransform();
memoryStream = new MemoryStream(System.Text.Encoding.Default.GetBytes(xml.OuterXml));
xPathDocument = new XPathDocument(new StreamReader(memoryStream));
sb = new StringBuilder();
// give the settings to the writer here
writer = XmlWriter.Create(sb, writerSettings);
// this is not mandatory, obviously, just passing parameters to my xslt file
foreach (KeyValuePair<string, object> parameter in parameters)
{
transformationArguments.AddParam(parameter.Key, string.Empty, parameter.Value);
}
using (Stream strm = Assembly.GetExecutingAssembly().GetManifestResourceStream("Lib.XSLTFile1.xslt"))
using (XmlReader reader = XmlReader.Create(strm))
{
transformer.Load(reader);
transformer.Transform(xPathDocument, transformationArguments, writer);
}
resultXml = new XmlDocument();
resultXml.LoadXml(sb.ToString());
// for testing only
File.AppendAllText(#"Your path goes here\result.xml", resultXml.OuterXml);
}
catch (Exception)
{
throw;
}
This is how I do it, but this code is specifically written to create an instance of a XmlDocument. I'm sure you can adapt to your needs.
I have an XmlSerializer which I use to Serialize an object to an XDocument.
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, object);
}
After this is done, I want to add a XDeclaration:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
I construct this XDeclaration as described below:
var decl = new XDeclaration("1.0", "UTF-8", "no");
However, when I try to add this XDeclartion to my XDocument, I get the following error:
System.ArgumentException : Non white space characters cannot be added to content.
I searched Google for some time but all I've found is adding the XDeclaration to the constructor of the XDocument which in my case (when filling it with a XmlWriter) is not acceptable.
Use property XDocument.Declaration
EDIT:
Sample code:
var xmlSerializer = new XmlSerializer(typeof(int));
var doc = new XDocument();
var decl = new XDeclaration("1.0", "utf-8", "no");
doc.Declaration = decl;
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, 1);
}
doc.Save(File.Create("x.xml"));
This code produced following output:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<int>1</int>