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);
Related
I neen apply simple xsl transform and continue work whith result data, but I wan't to save file. This is my code:
XslTransform xsl = new XslTransform();
var writer = new MemoryStream();
var xslDoc = new XPathDocument("107901.xslt");
xsl.Load(#"C:\Users\mak\Documents\Visual Studio 2015\Projects\SpellCheck\SpellCheck\GetAllValues.xslt");
xsl.Transform(xslDoc, null, writer);
writer.Position = 1;
var str = new StreamReader(writer);
var normalize = str.ReadToEnd().Trim('�');
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Save(normalize);
1) Why in variable str appears 2 symbol 65533?
2) Why variable normalize not save how xml file? Goes error 'not able to add it to the content characters than whitespace'
Maybe I doing all wrong and can easier.
Sorry for bad english and sanks for answer :-)
Don't understand question no.1 so I'll skip to question 2. If you care to read the documentation, it is clearly mentioned that the string argument of Save() should contains "The location of the file where you want to save the document". As for populating the XmlDocument instance from XML string, you can use LoadXml() :
.....
.....
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(normalize);
xmlDocument.Save("D:\path\to\your\output.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%).
This is the question I posted :
Hi, I have an XSLT code which needs to take parameters (say one or two) from C# code .. (If you want to know, why I need to do this, then let me explain, I have to parse an input XML from certain external application, however I need to edit data of some tags taking the values of some other application which could be defined in complex C# code, I don't have to worry about it) .. for the time being and for demo purpose, I need to declare some strings and pass them to XSLT following the action of triggering the transformation.
I tried to search google, but didn't work. If you get to know ANYTHING regarding this, please send me corresponding link or information ..
As I am not familiar with C# (thats the reason stuck with problem) simpler coding would help a lot ..
And also please specify which "project type" should I select ..
thanks in advance ..
And the solution is here:
http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.addparam.aspx
simple and works very conveniently ..
thanQ MandoMando and thanQ "stackoverflow"
Generally speaking, it's not necessary to create DOM objects like XmlDocument or XDocument to execute transforms.
XslCompiledTransfrom xslt = new XsltCompiledTransform()
xslt.Load(transformPath);
XsltArgumentList args = new XsltArgumentList();
args.AddParam("name", "myNamespace", value)
using (XmlReader xr = XmlReader.Create(inputPath))
using (XmlWriter xw = XmlWriter.Create(outputPath))
{
xslt.Transform(xr, args, xw);
}
Note that the Create() methods of XmlReader and XmlWriter have a formidable number of overloads. I use XmlWriter.Create(Console.Out) a lot when I'm prototyping.
Have your looked at this article? It talks about passing params to xslt in C#. I believe it is possible to do.
Quick and dirty:
XmlDocument x = new XmlDocument();
x.Load("yourxmldoc.xml");
XslTransform t = new XslTransform();
XsltArgumentList xslArg = new XsltArgumentList();
xslArg.AddParam("parameterName", "", parameterValue);
StringWriter swEndDoc = new System.IO.StringWriter();
t.Load("yourdoc.xslt");
t.Transform(x, xslArg, swEndDoc, null);
String output = swEndDoc.ToString();
This is fairly straightforward - note that I'm using XDocument and XslCompiledTransform:
XDocument xmlDocument = XDocument.Load(fromSource); // Or whatever means to get XML
XsltArgumentList xslArgs = new XsltArgumentList();
// For as many params as you need
xslArgs.AddParam("paramName", "", "paramValue");
// Create and load an XSLT transform - with params matching param names above
XslCompiledTransform t = new XslCompiledTransform();
t.Load(XSLTPath);
StringWriter outputDoc = new System.IO.StringWriter();
t.Transform(xmlDocument.CreateReader(), xslArgs, outputDoc);
String output = outputDoc.ToString();
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
I have an xml string which is very long in one line. I would like to save the xml string to a text file in a nice indent format:
<root><app>myApp</app><logFile>myApp.log</logFile><SQLdb><connection>...</connection>...</root>
The format I prefer:
<root>
<app>myApp</app>
<logFile>myApp.log</logFile>
<SQLdb>
<connection>...</connection>
....
</SQLdb>
</root>
What are .Net libraries available for C# to do it?
This will work for what you want to do ...
var samp = #"<root><app>myApp</app><logFile>myApp.log</logFile></root>";
var xdoc = XDocument.Load(new StringReader(samp), LoadOptions.None);
xdoc.Save(#"c:\temp\myxml.xml", SaveOptions.None);
Same result with System.Xml namespace ...
var xdoc = new XmlDocument();
xdoc.LoadXml(samp);
xdoc.Save(#"c:\temp\myxml.xml");
I'm going to assume you don't mean that you have a System.String instance with some XML in it, and I'm going to hope you don't create it via string manipulation.
That said, all you have to do is set the proper settings when you create your XmlWriter:
var sb = new StringBuilder();
var settings = new XmlWriterSettings {Indent = true};
using (var writer = XmlWriter.Create(sb, settings))
{
// write your XML using the writer
}
// Indented results available in sb.ToString()
Just another option:
using System.Xml.Linq;
public string IndentXmlString(string xml)
{
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}