Is XDocument.Parse different in Windows Phone 7? - c#

I am running the exact same code in a WP7 application and a C# 3.5 application. The WP7 application throws a NotSupportedException upon calling XDocument.Parse() while the C# 3.5 application parses the XML with no problems. Below is the code used:
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadThreadsComplete);
client.DownloadStringAsync(new Uri("http://us.battle.net/sc2/en/forum/40568/", UriKind.Absolute));
...
private static void DownloadThreadsComplete(object sender, DownloadStringCompletedEventArgs e)
{
var doc = XDocument.Parse(e.Result);
}
Any idea why this is happening? It's strange that it is failing when trying to parse an SC2 forum when a WoW forum works just fine (http://us.battle.net/wow/en/forum/984270/).
Edit:
The exception message is "NotSupportedException". Here's the full stack trace:
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text)
at SC2ForumReader.Pages.ForumViewerPage.DownloadThreadsComplete(Object sender, DownloadStringCompletedEventArgs e)
at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
Edit2:
I've done what was suggested and have looked at the output of the 2 different requests. Additionally in my 3.5 client application I forced the user-agent to be the same as it is in the WP7 emulator to ensure it's not the user-agent causing the issue.
Here's the doctype declaration copied from Visual Studio:
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
The doctypes are the same in each document but there are a few discrepancies in the files that stand out (it looks like there are a few extra characters inserted on the 3.5 side):
WP7 Emulator: StarCraft II
3.5 Application: StarCraft II

The problem is that XDocument.Parse enables DTD processing (which is normally disabled by default on a XmlTextReader) yet it does not supply a resolver. Try this code instead:
private static void DownloadThreadsComplete(object sender, DownloadStringCompletedEventArgs e)
{
XDocument doc;
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader reader = XmlReader.Create(new StringReader(e.Result), settings))
{
doc = XDocument.Load(reader);
}
// Do stuff with doc
}
OR:-
private static void DownloadThreadsComplete(object sender, DownloadStringCompletedEventArgs e)
{
XDocument doc;
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);
using (XmlReader reader = XmlReader.Create(new StringReader(e.Result), settings))
{
doc = XDocument.Load(reader);
}
// Do stuff with doc
}

Related

Which XML message generates an exception while doing ".LoadXml(xml_string)"?

I'm receiving text string messages, which should be XML-like.
However, sometimes that's not the case but I don't see what those messages look like:
Current code:
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
The Exception errormessage is quite elaborated (it mentions the wrong tags), but it does not mention the xml string itself:
Exception during data receiving event: [System.Xml.XmlException: Unexpected end of file has occurred. The following elements are not closed: ID, VM, HMS. Line 1, position 156.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ThrowUnclosedElements()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)
at ... Information.FromString(String xml) in C:\...\Information.cs:line 40
at ....<ExtractInformation>d__71.MoveNext() in C:\...\Extraction.cs:line 161
at some_other_function(Byte[] data) in C:\...\Extraction.cs:line 134]
System.Xml.XmlException: Unexpected end of file has occurred. The following elements are not closed: ID, VM, HMS. Line 1, position 156.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ThrowUnclosedElements()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)
at ... Information.FromString(String xml) in C:\...\Information.cs:line 40
at ....<ExtractInformation>d__71.MoveNext() in C:\...\Extraction.cs:line 161
at some_other_function(Byte[] data) in C:\...\Extraction.cs:line 134]
My idea was to add the xml-string to the Exception's Message property, but this seems to be read-only:
public static Information FromString(string xml)
{
var xmlDocument = new XmlDocument();
try
{
xmlDocument.LoadXml(xml);
}
catch (Exception ex)
{
ex.Message += "[" + xml + "]"; // <= compiler error CS0200
throw ex;
}
At that depth I don't have any logging possibilities and as I'm working with a server application, I can't show something on screen.
How can I add information to this Exception message (or to other properties/fields of the Exception)?

.NET XML Parser: Default attribute can not be applied as the attribute namespace is not mapped to a prefix in the instance document

I'm having a problem with .NET XML parser. When parsing a DITA document, the parser should add a default attribute value in a namespace of it's own, but when the namespace is not declared in the document, the parser throws an exception:
Default attribute 'http://dita.oasis-open.org/architecture/2005/:DITAArchVersion'
for element 'topic' could not be applied as the attribute namespace
is not mapped to a prefix in the instance document.
Here's a minimal sample topic that shows the behaviour...:
<?xml version="1.0" encoding="UTF-8"?>
<topic xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="so1"
xsi:noNamespaceSchemaLocation="urn:oasis:names:tc:dita:xsd:topic.xsd">
<title>StackOverflow!</title>
</topic>
Documents like this work fine in other environments, which leads me to thinking that we must somehow be missing something in the parser configuration. This is how the document is currently parsed:
XmlReaderSettings settings = new XmlReaderSettings();
if (validate) {
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationEventHandler += new ValidationEventHandler(
delegate(Object sender, ValidationEventArgs args) {
throw new Exception("Validation error for document " +
pathinfo + ": " + args.Message);
});
}
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.XmlResolver = new CatalogXmlResolver(/*...*/);
XmlReader reader = XmlReader.Create(new MemoryStream(data), settings);
XmlDocument doc = new XmlDocument();
if (!validate) { doc.PreserveWhitespace = true; }
doc.XmlResolver = getCatalog();
doc.Load(reader);
How can I tell the parser to also add the corresponding namespace as it adds the default attribute?
Edit: Here's the stack trace:
Void <parseDocument>b__0(System.Object, System.Xml.Schema.ValidationEventArgs) System.Exception: Validation error for document /temp/Untitled1.xml: Default attribute 'http://dita.oasis-open.org/architecture/2005/:DITAArchVersion' for element 'topic' could not be applied as the attribute namespace is not mapped to a prefix in the instance document.
at (...)
at System.Xml.Schema.XmlSchemaValidator.SendValidationEvent(XmlSchemaValidationException e, XmlSeverityType severity)
at System.Xml.Schema.XmlSchemaValidator.SendValidationEvent(String code, String[] args)
at System.Xml.Schema.XmlSchemaValidator.GetUnspecifiedDefaultAttributes(ArrayList defaultAttributes, Boolean createNodeData)
at System.Xml.XsdValidatingReader.ValidateAttributes()
at System.Xml.XsdValidatingReader.ProcessElementEvent()
at System.Xml.XsdValidatingReader.ProcessReaderEvent()
at System.Xml.XsdValidatingReader.Read()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
...so it really is a validation exception; now, if I validate using "MSXML.NET" (whatever that is) in oXygen, it says that the document is valid, as with the other parsers.

XML file as input to LoadXml returns xml exception c#

In my unit testing project, I have merged all my xml files into single xml file and need to send to webservice to seperate it into modules.
So, I have used the below code in my webservice,
//xmlString is my xml file content
try
{
XElement XmlDocument = new XElement("XMLDocument");
XmlDocument testDoc = new XmlDocument();
testDoc.LoadXml(xmlString);
XmlDocument = XElement.Load(new XmlNodeReader(testDoc));
}
catch (Exception ex)
{
string returnString = ex.StackTrace.ToString();
returnString += "XML breaks the code";
return returnString;
}
EDIT: While running this in finalbuilder, I am getting below exception
Exception Message: at ModuleSeparator.GetDetails(String xmlString) System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Results
Return value of 'ModuleSeparator' : at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)
at ModuleSeparator.GetDetails(String xmlString)XML breaks the code
Setting variable 'ModuleWiseTestCaseResults' to value ' at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)
at ModuleSeparator.GetDetails(String xmlString)XML breaks the code'.
My XML will look like,
<?xml version="1.0" encoding="utf-8"?>
<test-results name="Merged results" total="418" errors="0" failures="0" not-run="0" inconclusive="128" ignored="0" skipped="7" invalid="0" date="2016-03-08" time="10:47:33">
<test-suite type="Test Project" name="" executed="True" result="Skipped" success="True" time="311.143731" asserts="0">
<results></results>
</test-suite>
</test-results>

Biztalk Map Unit Testing Exception

I am trying to unit test a map with following code,
protected string Map(TransformBase map, string xml)
{
StringWriter str = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(str);
map.Transform.Transform(new XPathDocument(new StringReader(xml)), new XsltArgumentList(), writer);
return str.ToString();
}
And it's invoked as follows,
[Test]
public void Map_Test()
{
var result = Map(new TestMap(),File.ReadAllText(_dataDir.GetFiles("TestRequest.xml")[0].FullName));
Assert.IsTrue(result.Contains("4323432"));
}
This works fine for most of the maps, however if I uses a function from an external assembly, this does not works and fails with the error
Result Message: System.Xml.Xsl.XslTransformException : Cannot find a script or an extension object associated with namespace 'http://schemas.microsoft.com/BizTalk/2003/ScriptNS0'.
Result StackTrace:
at System.Xml.Xsl.Runtime.XmlQueryContext.InvokeXsltLateBoundFunction(String name, String namespaceUri, IList`1[] args)
at <xsl:template match="/workOrderRequest">(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, XPathNavigator {urn:schemas-microsoft-com:xslt-debug}current)
at <xsl:template match="/">(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, XPathNavigator {urn:schemas-microsoft-com:xslt-debug}current)
at Root(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime)
at Execute(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime)
at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlSequenceWriter results)
at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer)
at System.Xml.Xsl.XslCompiledTransform.Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results)
It is not possible to debug custom xslt with reference to external assembly.
Check this thread for more information
Edit : this might also interest you.
Finally, I have managed to do this with following code (BT 2013 R2),
The method Map do the actual mapping and returns the result xml,
Parameters,
map -> new object of the map type instance
xml -> source xml content
extObjects -> *_extxml.xml file content generated when executing validate instance on the map
Code
protected string Map(TransformBase map, string xml, string extObjects = null)
{
string result = string.Empty;
XslCompiledTransform transform = new XslCompiledTransform();
XsltSettings setting = new XsltSettings(false, true);
transform.Load(XmlReader.Create(new StringReader(map.XmlContent)), setting, new XmlUrlResolver());
using (StringWriter writer = new StringWriter())
{
transform.Transform(XmlReader.Create(new StringReader(xml)),
GetExtensionObjects(extObjects), XmlWriter.Create(writer));
result = writer.ToString();
}
return result;
}
protected XsltArgumentList GetExtensionObjects(string extObjects)
{
XsltArgumentList arguments = new XsltArgumentList();
if (extObjects == null)
return arguments;
XDocument extObjectsXDoc = XDocument.Parse(extObjects);
foreach (XElement node in extObjectsXDoc.Descendants("ExtensionObject"))
{
string assembly_qualified_name = String.Format("{0}, {1}", node.Attribute("ClassName").Value, node.Attribute("AssemblyName").Value);
object extension_object = Activator.CreateInstance(Type.GetType(assembly_qualified_name));
arguments.AddExtensionObject(node.Attribute("Namespace").Value, extension_object);
}
return arguments;
}
Sample usage
[Test]
public void Map_Test()
{
var result = Map(new A_To_B()
, File.ReadAllText("A.xml")
, File.ReadAllText("A_To_B_extxml.xml"));
Assert.IsNotNullOrEmpty(result);
}

How to resolve XSL includes in a Transformation that loads XSL from a String?

.NET 2.0/VS2005
I am trying to use the XslCompiledTransform class to perform a XSL Transformation. I have two XSL files, the first of which includes a reference to the other in the form of an <xsl:include> statement :
Main.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:include href="Included.xsl" />
...
...
</xsl:stylesheet>
Now, If I could load the "Main.xsl" file itself as a URI, my transformation code would be as simple as :
// This is a function that works. For demo only.
private string Transform(string xslFileURI)
{
XslCompiledTransform xslt = new XslCompiledTransform();
// This load works just fine, if I provide the path to "Main.xsl".
// The xsl:include is automatically resolved.
xslTransform.Load(xslFileURI);
StringWriter sw = new StringWriter();
xslt.Transform(Server.MapPath("~/XML/input.xml"), null, sw);
return sw.ToString();
}
The problem is that I receive the contents of the Main.xsl file as a string and need to load the string as an XmlReader/IXpathNavigable. This is a necessary restriction at this time. When I try to do the same using an XmlReader/XpathDocument, it fails because the code looks for "Included.xsl" in the C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ folder! Obviously, the XmlResolver is not able to resolve the relative URL because it only receives a string as input XSL.
My efforts in this direction look like:
// This doesn't work! Halp!
private string Transform(string xslContents)
{
XslCompiledTransform xslt = new XslCompiledTransform();
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = CredentialCache.DefaultCredentials;
//METHOD 1: This method does not work.
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = resolver;
XmlReader xR = XmlReader.Create(new StringReader(xslContents), settings);
xslt.Load(xR); // fails
// METHOD 2: Does not work either.
XPathDocument xpDoc = new XPathDocument(new StringReader(xslContents));
xslt.Load(xpDoc, new XsltSettings(true, true), resolver); //fails.
StringWriter sw = new StringWriter();
xslt.Transform(Server.MapPath("~/XML/input.xml"), null, sw);
return sw.ToString();
}
I have tried to use the ResolveUri method of the XmlUrlResolver to obtain a Stream referencing the XSL file to be included, but am confused as to how to use this Stream. IOW, how do I tell the XslCompiledTransform object to use this stream in addition to the Main.xsl XmlReader:
Uri mainURI = new Uri(Request.PhysicalApplicationPath + "Main.xsl");
Uri uri = resolver.ResolveUri(mainURI, "Included.xsl");
// I can verify that the Included.xsl file loads in the Stream below.
Stream s = resolver.GetEntity(uri, null, typeof(Stream)) as Stream;
// How do I use this Stream in the function above??
Any help is greatly appreciated. Sorry for the long post!
For your reference, the Exception StackTrace looks like this:
[FileNotFoundException: Could not find file 'C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\Included.xsl'.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +328
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) +1038
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) +113
System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) +78
System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) +51
System.Xml.Xsl.Xslt.XsltLoader.CreateReader(Uri uri, XmlResolver xmlResolver) +22
System.Xml.Xsl.Xslt.XsltLoader.LoadStylesheet(Uri uri, Boolean include) +33
System.Xml.Xsl.Xslt.XsltLoader.LoadInclude() +349
System.Xml.Xsl.Xslt.XsltLoader.LoadRealStylesheet() +704
System.Xml.Xsl.Xslt.XsltLoader.LoadDocument() +293
System.Xml.Xsl.Xslt.XsltLoader.LoadStylesheet(XmlReader reader, Boolean include) +173
Use a custom XmlUrlResolver
class MyXmlUrlResolver : XmlUrlResolver
{
public override Uri ResolveUri(Uri baseUri, string relativeUri)
{
if (baseUri != null)
return base.ResolveUri(baseUri, relativeUri);
else
return base.ResolveUri(new Uri("http://mypath/"), relativeUri);
}
}
And use it in load function of XslCompiledTransform,
resolver=new MyXmlUrlResolver();
xslt.Load(xR,null,resolver);
As Gee's answer mentions, you want to use a custom XmlResolver (of which XmlUrlResolver is already derived), but if you also override the method GetEntity you can resolve references in the primary XSLT document in fun and interesting ways. A deliberately simple example of how you could resolve the reference to Included.xsl:
public class CustomXmlResolver : XmlResolver
{
public CustomXmlResolver() { }
public override ICredentials Credentials
{
set { }
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
MemoryStream entityStream = null;
switch (absoluteUri.Scheme)
{
case "custom-scheme":
string absoluteUriOriginalString = absoluteUri.OriginalString;
string ctgXsltEntityName = absoluteUriOriginalString.Substring(absoluteUriOriginalString.IndexOf(":") + 1);
string entityXslt = "";
// TODO: Replace the following with your own code to load data for referenced entities.
switch (ctgXsltEntityName)
{
case "Included.xsl":
entityXslt = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template name=\"Included\">\n\n </xsl:template>\n</xsl:stylesheet>";
break;
}
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] entityBytes = utf8Encoding.GetBytes(entityXslt);
entityStream = new MemoryStream(entityBytes);
break;
}
return entityStream;
}
public override Uri ResolveUri(Uri baseUri, string relativeUri)
{
// You might want to resolve all reference URIs using a custom scheme.
if (baseUri != null)
return base.ResolveUri(baseUri, relativeUri);
else
return new Uri("custom-scheme:" + relativeUri);
}
}
When you load the Main.xsl document you'd change the relevant code to the following:
xslt.Load(xpDoc, new XsltSettings(true, true), new CustomXmlResolver());
The above example was based on info I picked-up in the MSDN article Resolving the Unknown: Building Custom XmlResolvers in the .NET Framework.
I am probably missing the obvious but is there a reason you don't just change the URI of Included.xsl to be a true URL? This could either be done in the XSL doc if you have access or using string manipulation otherwise?
I already have success with doing transformations using all in memory:
Having a xslt containing the following includes:
import href="Common.xslt" and
import href="Xhtml.xslt"
private string Transform(string styleSheet, string xmlToParse)
{
XslCompiledTransform xslt = new XslCompiledTransform();
MemoryResourceResolver resolver = new MemoryResourceResolver();
XmlTextReader xR = new XmlTextReader(new StringReader(styleSheet));
xslt.Load(xR, null, resolver);
StringWriter sw = new StringWriter();
using (var inputReader = new StringReader(xmlToParse))
{
var input = new XmlTextReader(inputReader);
xslt.Transform(input,
null,
sw);
}
return sw.ToString();
}
public class MemoryResourceResolver : XmlResolver
{
public override object GetEntity(Uri absoluteUri,
string role, Type ofObjectToReturn)
{
if (absoluteUri.ToString().Contains("Common"))
{
return new MemoryStream(Encoding.UTF8.GetBytes("Xml with with common data"));
}
if (absoluteUri.ToString().Contains("Xhtml"))
{
return new MemoryStream(Encoding.UTF8.GetBytes("Xml with with xhtml data"));
}
return "";
}
}
Note that absolutely all content is as strings: styleSheet, xmlToParse and the content of the "Common" and "Xhtml" imports

Categories