Converting XML/XSLT to HTML - c#

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.

Related

How to check if XMLReader has valid XML without reading so as to write complete using XMLWriter?

I'm trying to write a string(which is nothing but XMLNodes) into a new XML File using XMLWriter. Few of the strings are valid XML content while few of the string aren't.
String Input:
1.
<Test>
<A a="Hello"></A>
<B b="Hello"></B>
</Test>
Hello
This is Sample String but not XML
Code :
using (XmlWriter writer = XmlWriter.Create(#"C:\\Test.XML"))
{
writer.WriteStartDocument();
string scontent2 = "Hello This is Sample String but not XML";
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
try{
using (StringReader stringReader = new StringReader(scontent))
using (XmlReader xmlReader = XmlReader.Create(stringReader, settings))
{
writer.WriteStartElement("Test");
writer.WriteNode(xmlReader, true);
writer.WriteEndElement();
}catch(XMLException exception){}
}
Expected Output:
The Test element must also not be created if the Exception occurs. If I use, scontent.Read() or any such, the problem is since the pointer moves to a node, the writer.WriteNode(scontent,true) wont write entire nodes(if there are more than two nodes) For ex. <A a="Hello"></A><B b="Hello"></B>. In this case, I've write all nodes using WriteNode for which XMLReader must be in Initial State(XmlReader.State).

Generate XML from C# Code

I have to generate specific XML data from code.
The XML needs to look like this
<this:declarationIdentifier xmlns:this="demo.org.uk/demo/DeclarationGbIdentifier"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="demo.org.uk/demo/DeclarationGbIdentifier DeclarationGbIdentifier.xsd"
xmlns:nsIdentity="demo.org.uk/demo/DeclarationGbIdentityType">
<this:declarationIdentity>
<nsIdentity:declarationUcr>Hello World</nsIdentity:declarationUcr>
</this:declarationIdentity>
</this:declarationIdentifier>
I have dabbled with XmlSerializer and XDocument but cant get the output to match this exactly
Please help.
I believe this will produce your desired output. There possibly is a simpler way this is just off the cuff to get you started. With the prefixes that you are requiring I would look up XmlDocument and adding namespaces to it to have a better understanding of what the code below is doing. Also what I would do is attempt to acquire the XSD schema file and use the XSD.exe to build a .cs file and then you can move forward with the XmlSerializer. If you move forward with the code below i highly suggest moving off your namespaceuri's into some soft of settings file so you can easily modify them in the event they change.
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("this", "declarationIdentifier", "demo.org.uk/demo/DeclarationGbIdentifier");
root.SetAttribute("xmlns:this", "demo.org.uk/demo/DeclarationGbIdentifier");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
//Just setting an Attribute of xsi:schemaLocation it would always drop the xsi prefix in the xml so this is different to accomodate that
XmlAttribute schemaAtt = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
schemaAtt.Value = "demo.org.uk/demo/DeclarationGbIdentifier DeclarationGbIdentifier.xsd";
root.Attributes.Append(schemaAtt);
root.SetAttribute("xmlns:nsIdentity", "demo.org.uk/demo/DeclarationGbIdentityType");
doc.AppendChild(root);
XmlElement declarationIdentity = doc.CreateElement("this", "declarationIdentity", "demo.org.uk/demo/DeclarationGbIdentifier");
XmlElement declarationUcr = doc.CreateElement("nsIdentity","declarationUcr","demo.org.uk/demo/DeclarationGbIdentityType");
declarationUcr.InnerText = "Hello World";
declarationIdentity.AppendChild(declarationUcr);
doc.DocumentElement.AppendChild(declarationIdentity);
To output this as a string or dump it off to a file you can use the following operations, I output to a file as well as output to the console in my test app.
using (var stringWriter = new StringWriter())
using (StreamWriter writer = new StreamWriter(#"C:\<Path to File>\testing.xml"))
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
doc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
writer.Write(stringWriter.GetStringBuilder().ToString());
Console.WriteLine(stringWriter.GetStringBuilder().ToString());
}

Creating an XML with multiple root elements

I'm trying to create an XML with multiple root elements. I can't change that because that is the way I'm supposed to send the XML to the server. This is the error I get when I try to run the code:
System.InvalidOperationException: This operation would create an incorrectly structured document.
Is there a way to overwrite this error and have it so that it ignores this?
Alright so let me explain this better:
Here is what I have
XmlDocument doc = new XmlDocument();
doc.LoadXml(_application_data);
Now that creates the XML document and I can add a fake root element to it so that it works. However, I need to get rid of that and convert it into a DocumentElement object.
How would I go about doing that?
Specify Fragment when creating XmlWriter as shown here
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.CloseOutput = false;
// Create the XmlWriter object and write some content.
MemoryStream strm = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(strm, settings))
{
writer.WriteElementString("orderID", "1-456-ab");
writer.WriteElementString("orderID", "2-36-00a");
writer.Flush();
}
If it has multiple root elements, it's not XML. If it resembles XML in other ways, you could place everything under a root element, then when you send the string to the server, you just combine the serialized child elements of this root element, or as #Austin points out, use an inner XML method if available.
just create an XML with single root then get it's content as XML text.
you are talking about XML fragment anyways, since good xml has only one root.
this is sample to help you started:
var xml = new XmlDocument();
var root = xml.CreateElement("root");
root.AppendChild(xml.CreateElement("a"));
root.AppendChild(xml.CreateElement("b"));
Console.WriteLine(root.InnerXml); // outputs "<a /><b />"

How to pass and get the string based xml data in xslt transform using C#?

I want to convert one xml file into another xml file using xslt.here, i can able to pass the input document to the XPathDocument and also save the output file in disk by passing outfile into XmlTextWriter.
But now my problem is... i have my input is in string format and i also want output as a string.Instead of passing the location of the input file, i want to pass string that contains the xml data.
so i have to pass string object into xpathDoccument in someway and also get the resultant xml file as a string.Instead of save the output as a file,i want output as a string.
XPathDocument xpathDoc = new XPathDocument("C:\\InputXml.xml");
XslCompiledTransform xslt = new XslCompiledTransform();
string xsltFile = "C:\\conversion.xslt";
xslt.Load(xsltFile);
string outputFile = "C:\\myHtml.html";
XmlTextWriter writer = new XmlTextWriter(outputFile, null);
xslt.Transform(xpathDoc, null, writer);
writer.Close();
Please guide me to get out of this issue...
XPathDocument accepts TextReader. You can give a stream as new XPathDocument(new StringReader(xmlstring)). Similarly XmlTextWriter accepts TextWriter. So you can pass a StringWriter.
--edit--
var sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
xslt.Transform(xpathDoc, null, writer);
var str= sw.ToString();
Try this,
XslTransform xTrans = new XslTransform();
xTrans.Load(nodeXsltPath); //xsl file path
XmlDocument input= new XmlDocument();
XmlDocument output= new XmlDocument();
input.LoadXml(xmlString); /* Xml string to be loaaded */
output.Load(xTrans.Transform(input,null,new XmlUrlResolver()));
output.Save(filePathtoSave);

Make xml more readable

Is there any way to take an xml string in .net and make it easyer to read?
what i mean is can i convert this:
<element1><element2>some data</element2></element1>
to this:
<element1>
<element2>
some data
</element2>
</element1>
is there any built in class for this? as sql server 2005 seems to remove all formatting on xml to save space or some thing...
If you're using .NET 3.5, you can load it as an XDocument and then just call ToString() which will indent it appropriately. For example:
using System;
using System.Xml.Linq;
public class Test
{
static void Main()
{
string xml = "<element1><element2>some data</element2></element1>";
XDocument doc = XDocument.Parse(xml);
xml = doc.ToString();
Console.WriteLine(xml);
}
}
Result:
<element1>
<element2>some data</element2>
</element1>
If you're writing it to a file or other stream, then XDocument.Save will (by default) indent it too.
(I believe XElement has all the same features, if you don't really need an XDocument.)
How do you save / write the XML back to a file ?
You can create an XmlWriter and pass it an XmlWriterSettings instance, where you set the Indent property to true:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create (outputStream, settings);
You can load the string into an XDocument object and save it to a string again:
XDocument doc = XDocument.Load(new StringReader(xmlString));
StringWriter writer = new StringWriter();
doc.Save(writer);
string readable = writer.ToString();
That will give you the xml formatted this way:
<?xml version="1.0" encoding="utf-16"?>
<element1>
<element2>some data</element2>
</element1>
Have a look at
XmlWriterSettings
http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx
you can define Indent and IndentChars
First of all, you have tagged C# and VB.NET both. So my answer will be for both of them.
You can define function which get XML string as a parameter in type of String.
Let's say;
You created a function as :
[VB]
Private Function PrettyXML(XMLString As String) As String
Dim sw As New StringWriter()
Dim xw As New XMLWriter(sw)
xw.Formatiing = Formatting.Indented
xw.Indentation = 4
Dim doc As New XMLDocument
doc.LoadXML(XMLString)
doc.Save(xw)
Return sw.ToString()
End Function
Then you can simpyl call this function as:
Dim myXML As String = "<element1><element2>some data</element2></element1>"
Dim myPrettyXML As String
myPrettyXML = PrettyXML(myPrettyXML)
[C#]
Private String PrettyXML(string XMLString)
{
StringWriter sw = new StringWriter();
XMLTextWriter xw = new XmlTextWriter(sw);
xw.Formatiing = Formatting.Indented;
xw.Indentation = 4;
XmlDocument doc = new XmlDocument();
doc.Save(xm);
return sw.ToString();
}
Then you can simply call this function as:
string myXML = "<element1><element2>some data</element2></element1>";
string myPrettyXML = "";
myPrettyXML = PrettyXML(myPrettyXML);
NOTE: I have not tried C# version, but it should work.
Hope this helps..

Categories

Resources