Exclude XML directive from XslCompiledTransform.Transform output - c#

I'm using an XsltCompiledTransform to transform some XML into a fragment of HTML (not a complete HTML document, just a DIV that I will include in page generated elsewhere).
I'm doing the transformation as follows:
StringBuilder output = new StringBuilder();
XmlReader rawData = BusinessObject.GetXml();
XmlWriter transformedData = XmlWriter.Create(output);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("stylesheet.xslt");
transform.Transform(rawData, transformedData);
Response.Write(output.ToString());
My problem is that the result of the transform always begins with this XML directive:
<?xml version="1.0" encoding="utf-16"?>
How do I prevent this from appearing in my transformed data?
EDIT:
I'm telling the XSLT that I don't want it to output an xml declaration with
<xsl:output method="html" version="4.0" omit-xml-declaration="yes"/>
but this seems to have no effect on the directive appearing in my output.
Interestingly, both my XML data source and my XSLT transform specify themselves as UTF-8 not UTF-16.
UPDATE:
The UTF-16 seems to be appearing because I'm using a string(builder) as an output mechanism. When I change the code to use a MemoryStream instead of a StringBuilder, my UTF-8 encoding is preserved. I'm guessing this has something to do with the internal workings of the string type and how it deals with encoding.

You need to use an XmlWriterSettings object. Set its properties to omit the XML declaration, and pass it to the constructor of your XmlWriter.
StringBuilder output = new StringBuilder();
XmlReader rawData = BusinessObject.GetXml();
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
using (XmlWriter transformedData = XmlWriter.Create(output, writerSettings))
{
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("stylesheet.xslt");
transform.Transform(data, transformedData);
Response.Write(output.ToString());
}

The easiest way would be to add this node to your XSLT:
<xsl:output
method="html"
omit-xml-declaration="yes"/>

Related

Converting XML/XSLT to HTML

I have the following XML that came from TNT that I should be able to use to create a shipping label:
https://codebeautify.org/xmlviewer/cb55b98e
I have been supplied with the following XSL file:
https://express.tnt.com/expresswebservices-website/stylesheets/HTMLAddressLabelRenderer.xsl
I have attempted to combine them with the following code:
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment,
CloseOutput = false,
};
// populate the root element with the XML of the address label
XElement root = new XElement("root", XElement.Parse(await _engine.GetDocument("GET_LABEL", code)));
XDocument newTree = new XDocument();
using (XmlWriter writer = XmlWriter.Create(newTree.CreateWriter(), settings))
{
XslCompiledTransform xslt = new XslCompiledTransform();
XsltSettings trev = new XsltSettings
{
EnableDocumentFunction = true,
EnableScript = true
};
xslt.Load(#"C:\Users\Trevo\Desktop\HTMLAddressLabelRenderer.xsl", trev, null);
xslt.Transform(root.CreateReader(), writer);
writer.Close();
newTree.Save(#"C:\Users\Trevo\Desktop\result.html");
}
the HTML only contains the script and head properties and the body is completely empty.
I cannot work out why it isn't working. I have considered that the "root" is not the correct XName but unsure how to work out what it should be.
Any help would be greatly appreciated!
Try this freeformatter
For XML Input, on the first line, enter the below xml, then paste your xml code
<?xml version="1.0"?>
For XML Output, just paste your xsl code.
Click Transform XML. Just play around with the formatter but it will give html output.

Why XDocument encoding type changed while use XDocument's WriteTo method

I have used XDocument to create simple xml document.I have created document with XDocument and XDeclaration.
XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root", "Content"));
If i save this document to file means the encoding type is not changed.
using (TextWriter sw = new StreamWriter(#"C:\sample.txt", false)){
encodedDoc8.Save(sw);
}
Output:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>Content</Root>
But,if I use XDocument's WriteTo method to print the xml means encoding type is changed.
using (XmlWriter writ = XmlWriter.Create(Console.Out))
{
encodedDoc8.WriteTo(writ);
}
Output:
<?xml version="1.0" encoding="IBM437" standalone="yes"?><Root>Content</Root>
Why this happened?.Please update your answers.Thanks in advance.
If you look at the reference source for XmlWriter.Create, the chain of calls would eventually lead to this constructor:
public XmlTextWriter(TextWriter w) : this() {
textWriter = w;
encoding = w.Encoding;
xmlEncoder = new XmlTextEncoder(w);
xmlEncoder.QuoteChar = this.quoteChar;
}
The assignment encoding = w.Encoding provides an explanation to what is happening in your case: the Encoding setting of the Console.Out text writer is copied to the encoding setting of the newly created XmlTextWriter, replacing the encoding that you supplied in the XDocument.

C# XMLElement.OuterXML in a single line rather than format

I am trying to log some XML responses from a WCF Service using log4net.
I want the output of the XML file to the log to be in properly formed XML. The request comes in as an XMLElement.
Example:
The request comes in as this:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationEvent xmlns="http://courts.wa.gov/INH_TV/ApplicationEvent.xsd">
<Severity xmlns="">Information</Severity>
<Application xmlns="">Application1</Application>
<Category xmlns="">Timings</Category>
<EventID xmlns="">1000</EventID>
<DateTime xmlns="">2012-09-02T12:05:15.234Z</DateTime>
<MachineName xmlns="">Server1</MachineName>
<MessageID xmlns="">10000000-0000-0000-0000-000000000000</MessageID>
<Program xmlns="">Progam1</Program>
<Action xmlns="">Entry</Action>
<UserID xmlns="">User1</UserID>
</ApplicationEvent>
Then if I output this value to log4net.
logger.Info(request.OuterXml);
I get the entire document logged in a single line like so:
<ApplicationEvent xmlns="http://courts.wa.gov/INH_TV/ApplicationEvent.xsd"><Severity xmlns="">Information</Severity><Application xmlns="">Application1</Application><Category xmlns="">Timings</Category><EventID xmlns="">1000</EventID><DateTime xmlns="">2012-09-02T12:05:15.234Z</DateTime><MachineName xmlns="">Server1</MachineName><MessageID xmlns="">10000000-0000-0000-0000-000000000000</MessageID><Program xmlns="">Progam1</Program><Action xmlns="">Entry</Action><UserID xmlns="">User1</UserID></ApplicationEvent>
I would like it to display in the log.txt file formatted correctly as it came in. So far the only way I have found to do this is to convert it to an XElement like so:
XmlDocument logXML = new XmlDocument();
logXML.AppendChild(logXML.ImportNode(request, true));
XElement logMe = XElement.Parse(logXML.InnerXml);
logger.Info(logMe.ToString());
This doesn't seem like good programming to me. I have been searching the documentation and I can't find a built-in way to output this correctly without converting it.
Is there an obvious, better way that I am just missing?
edit1: Removed ToString() since OuterXML is a String value.
edit2: I answered my own question:
So I did some more research, and I guess I missed a piece of code in the documentation.
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.outerxml.aspx
I have it down to:
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings xws = new XmlWriterSettings();
xws.Indent = true;
using (XmlWriter xmlWriter = XmlWriter.Create(ms, xws))
{
request.WriteTo(xmlWriter);
}
ms.Position = 0; StreamReader sr = new StreamReader(ms);
string s = sr.ReadToEnd(); // s will contain indented xml
logger.Info(s);
}
Which is a little more efficient than my current method despite being more verbose.
XElement parse is the cleanest way. You can save a line or two with:
logger.Info(XElement.Parse(request.OuterXml).ToString());

Deserialization error in XML document(1,1)

I have an XML file that I deserialize, the funny part is the XML file is the was serialized
using the following code:
enter code here
var serializer = new XmlSerializer(typeof(CommonMessage));
var writer = new StreamWriter("OutPut.txt");
serializer.Serialize(writer, commonMessage);
writer.Close();
And i m trying to deserialized it again to check if the output match the input.
anyhow here is my code to deserialize:
var serializer = new XmlSerializer(typeof(CommonMessage));
var reader = new StringReader(InputFileName);
CommonMessage commonMessage = (CommonMessage)serializer.Deserialize(reader);
Replace StringReader with StreamReader and it will work fine. StringReader reads value from the string (which is file name in your case).
I just had the same error message but different error source. In case someone has the same problem like me. I chopped off the very first char of my xml string by splitting strings. And the xml string got corrupted:
"?xml version="1.0" encoding="utf-16"?> ..." // my error
"<?xml version="1.0" encoding="utf-16"?> ..." // correct
(1,1) means basically first char of the first line is incorrect and the string can't be deserialized.
include in your CommonMessage class the XmlRoot element tag with your xmlroot eg:[XmlRoot("UIIVerificationResponse")]
You should disable the order mark in the StreamWriter constructor like this:
UTF8Encoding(false)
Full sample:
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
xmlSerializer.Serialize(writer, objectToSerialize, ns);
return Encoding.UTF8.GetString(stream.ToArray());
}

How to set xmlns when serializing object in c#

I am serializing an object in my ASP.net MVC program to an xml string like this;
StringWriter sw = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(mytype));
s.Serialize(sw, myData);
Now this give me this as the first 2 lines;
<?xml version="1.0" encoding="utf-16"?>
<GetCustomerName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
my question is,
How can I change the xmlns and the encoding type, when serializing?
Thanks
What I found that works was to add this line to my class,
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://myurl.com/api/v1.0", IsNullable = true)]
and add this to my code to add namespace when I call serialize
XmlSerializerNamespaces ns1 = new XmlSerializerNamespaces();
ns1.Add("", "http://myurl.com/api/v1.0");
xs.Serialize(xmlTextWriter, FormData, ns1);
as long as both namespaces match it works well.
The XmlSerializer type has a second parameter in its constructor which is the default xml namespace - the "xmlns:" namespace:
XmlSerializer s = new XmlSerializer(typeof(mytype), "http://yourdefault.com/");
To set the encoding, I'd suggest you use a XmlTextWriter instead of a straight StringWriter and create it something like this:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
XmlTextWriter xtw = XmlWriter.Create(filename, settings);
s.Serialize(xtw, myData);
In the XmlWriterSettings, you can define a plethora of options - including the encoding.
Take a look at the attributes that control XML serialization in .NET.
Specifically, the XmlTypeAttribute may be useful for you. If you're looking to change the default namespace for you XML file, there is a second parameter to the XmlSerializer constructor where you can define that.

Categories

Resources