C# XSLT transform adding and to the output - c#

I have an XSLT transform issue:
style="width:{Data/PercentSpaceUsed}%;"
And the value of Data/PercentSpaceUsed is integer 3.
And it outputs:
style="width:
3
%;"
instead of what I expected:
style="width:3%;"
Here's the code that does the transform: xslt_xslt is the transform xml, sw.ToString() contains the 
 and
which I did not expect.
var xslTransObj = new XslCompiledTransform();
var reader = new XmlTextReader(new StringReader(xslt_xslt));
xslTransObj.Load(reader);
var sw = new StringWriter();
var writer = new XmlTextWriter(sw);
xslTransObj.Transform(new XmlTextReader(new StringReader(xslt_data)), writer);
ResultLiteral.Text = sw.ToString();

The
are carriage returns and line feeds either within your XML or your XSLT. Make sure the xml is like
<Value>3</Value>
Rather than
<Value>
3
</Value>
I believe there is a way to stop whitespace being used within your transformation although I don`t know it off the top of my head.

You're getting whitespace from the source document. Use
style="width:{normalize-space(Data/PercentSpaceUsed)}%;"
to strip out the whitespace. The other option in your case would be to use
style="width:{number(Data/PercentSpaceUsed)}%;"

try
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineHandling = NewLineHandling.None;
XmlWriter writer = XmlWriter.Create(xmlpath, settings);
for input whitespace to be preserved on output for attribute values.
note: with above settings, tabs are used for indentation

Related

Missing xml header when convert json to xml in C# [duplicate]

Consider the following simple code which creates an XML document and displays it.
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("root");
xml.AppendChild(root);
XmlComment comment = xml.CreateComment("Comment");
root.AppendChild(comment);
textBox1.Text = xml.OuterXml;
it displays, as expected:
<root><!--Comment--></root>
It doesn't, however, display the
<?xml version="1.0" encoding="UTF-8"?>
So how can I get that as well?
Create an XML-declaration using XmlDocument.CreateXmlDeclaration Method:
XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);
Note: please take a look at the documentation for the method, especially for encoding parameter: there are special requirements for values of this parameter.
You need to use an XmlWriter (which writes the XML declaration by default). You should note that that C# strings are UTF-16 and your XML declaration says that the document is UTF-8 encoded. That discrepancy can cause problems. Here's an example, writing to a file that gives the result you expect:
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("root");
xml.AppendChild(root);
XmlComment comment = xml.CreateComment("Comment");
root.AppendChild(comment);
XmlWriterSettings settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
ConformanceLevel = ConformanceLevel.Document,
OmitXmlDeclaration = false,
CloseOutput = true,
Indent = true,
IndentChars = " ",
NewLineHandling = NewLineHandling.Replace
};
using ( StreamWriter sw = File.CreateText("output.xml") )
using ( XmlWriter writer = XmlWriter.Create(sw,settings))
{
xml.WriteContentTo(writer);
writer.Close() ;
}
string document = File.ReadAllText( "output.xml") ;
XmlDeclaration xmldecl;
xmldecl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDocument.DocumentElement;
xmlDocument.InsertBefore(xmldecl, root);

Serializing an XDocument

I am trying to quickly and correctly serialize an XDocument object. I have tried several things, but this last one (found it here) seems simple and straightforward:
StringBuilder b = new StringBuilder();
XmlWriterSettings sett = new XmlWriterSettings();
sett.Encoding = Encoding.UTF8;
XmlWriter xw = XmlWriter.Create(b, sett);
doc.Save(xw);
String r = b.ToString();
However, at the end, r is just an empty string. Am I missing something? Why is it so hard to correctly serialize an XDocument object?
The frustrating thing is that if I call doc.ToString() I get a nice serialized XML string, without declaration. If I call doc.ToString(true) I get an empty string (doc.Declaration is set).
I figured it out. Still not convinced this is the "right" way to do it, but here goes:
MemoryStream s = new MemoryStream();
using (TextWriter b = new StreamWriter(s, Encoding.UTF8))
doc.Save(b);
String r = Encoding.UTF8.GetString(s.ToArray());
This results in a correctly encoded and correctly declared XML string.

Xml within an Xml

I basically want to know how to insert a XmlDocument inside another XmlDocument.
The first XmlDocument will have the basic header and footer tags.
The second XmlDocument will be the body/data tag which must be inserted into the first XmlDocument.
string tableData = null;
using(StringWriter sw = new StringWriter())
{
rightsTable.WriteXml(sw);
tableData = sw.ToString();
}
XmlDocument xmlTable = new XmlDocument();
xmlTable.LoadXml(tableData);
StringBuilder build = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(build, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
writer.WriteStartElement("dataheader");
//need to insert the xmlTable here somehow
writer.WriteEndElement();
}
Is there an easier solution to this?
Use importNode feature in your document parser.
You can use this code based on CreateCDataSection method
// Create an XmlCDataSection from your document
var cdata = xmlTable.CreateCDataSection("<test></test>");
XmlElement root = xmlTable.DocumentElement;
// Append the cdata section to your node
root.AppendChild(cdata);
Link : http://msdn.microsoft.com/fr-fr/library/system.xml.xmldocument.createcdatasection.aspx
I am not sure what you are really looking for but this can show how to merge two xml documents (using Linq2xml)
string xml1 =
#"<xml1>
<header>header1</header>
<footer>footer</footer>
</xml1>";
string xml2 =
#"<xml2>
<body>body</body>
<data>footer</data>
</xml2>";
var xdoc1 = XElement.Parse(xml1);
var xdoc2 = XElement.Parse(xml2);
xdoc1.Descendants().First(d => d.Name == "header").AddAfterSelf(xdoc2.Elements());
var newxml = xdoc1.ToString();
OUTPUT
<xml1>
<header>header1</header>
<body>body</body>
<data>footer</data>
<footer>footer</footer>
</xml1>
You will need to write the inner XML files in CDATA sections.
Use writer.WriteCData for such nodes, passing in the inner XML as text.
writer.WriteCData(xmlTable.OuterXml);
Another option (thanks DJQuimby) is to encode the XML to some XML compatible format (say base64) - note that the encoding used must be XML compatible and that some encoding schemes will increase the size of the encoded document (base64 adds ~30%).

Applying an XSLT Transform to a DataSet (ADO.NET)

There is a nice example on the Microsoft Website (Even vor .Net 4)
Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet)
Dim xslTran As XslTransform = New XslTransform
xslTran.Load("transform.xsl")
Dim writer As XmlTextWriter = New XmlTextWriter("xslt_output.html", System.Text.Encoding.UTF8)
xslTran.Transform(xmlDoc, Nothing, writer)
http://technet.microsoft.com/en-us/query/8fd7xytc
No unfortunately XmlDataDocument is deprecated, but nobody seems to have a good answer on how to replace it in this situation?
You can use the following code.
Use DataSet.GetXml() to get the xml as string and then create an XDocument by parsing the string:
string xml = dataSet.GetXml();
XDocument document = XDocument.Parse(xml);
The setup of the transformation and its output is the same, except using XslCompiledTransform:
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("transform.xsl");
XmlTextWriter writer = new XmlTextWriter("Output.xml", System.Text.Encoding.UTF8);
And then you can use the XslCompiledTransform.Transform() overload that takes a reader as the first argument, which you can get from calling XDocument.CreateReader():
transform.Transform(Document.CreateReader(), writer);

How to ignore leading whitespace in XML file?

I need to load xml from a file into an XmlDocument. The problem is that the file contains some leading whitespace. (I have no control over the system that produces the file.)
Is there any clean/easy way to ignore or strip those characters?
string SamplelRequestFile = #"C:\example.xml";
XmlDocument docXML = new XmlDocument();
XmlTextReader xReader = new XmlTextReader(SamplelRequestFile);
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.XmlResolver = null;
ReaderSettings.ProhibitDtd = false;
docXML.Load(xReader);
example.xml (note the leading spaces)
<?xml version="1.0" ?>
<myRoot>
<someElement />
</myRoot>
You'll just have to do something like
using (StreamReader sr = new StreamReader(#"C:\example.xml"))
{
XmlDocument docXML = new XmlDocument();
docXML.LoadXml(sr.ReadToEnd().Trim());
...
}
here is a sample that works:
string file = #"C:\example.xml";
XmlDocument docXML = new XmlDocument();
using (TextReader x = new StreamReader(file))
{
while (x.Peek() == ' ')
x.Read();
docXML.Load(x);
}
This is an invalid XML.
According to XML Specification, pi or processing-instructions must be the first characters if they are present.
I suggest you pre-process the XML by trimming the XML.
Workaround:
string content = File.ReadAllText(#"C:\example.xml");
XmlDocument doc = new XmlDocument();
doc.LoadXml(content.Trim());
Create a Stream and a StreamReader on the file yourself, then Peek() and consume characters from the stream as long as you see whitespace. Once you're sure that the next character is <, pass the stream to the XmlTextReader constructor.
Have you tried adding this flag ?
ReaderSettings.IgnoreWhitespace = true;
string newXml = string.TrimLeft(oldXml);

Categories

Resources