19

I have the following variable that accepts a file name:

var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None };
var xd = new XmlDocument();
xd.Load(xtr);

I would like to change it so that I can pass in an object. I don't want to have to serialize the object to file first.

Is this possible?

Update:

My original intentions were to take an xml document, merge some xslt (stored in a file), then output and return html... like this:

public string TransformXml(string xmlFileName, string xslFileName)
{
     var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None };
     var xd = new XmlDocument();
     xd.Load(xtr);

     var xslt = new System.Xml.Xsl.XslCompiledTransform();
     xslt.Load(xslFileName);
     var stm = new MemoryStream();
     xslt.Transform(xd, null, stm);
     stm.Position = 1;
     var sr = new StreamReader(stm);
     xtr.Close();
     return sr.ReadToEnd();
}

In the above code I am reading in the xml from a file. Now what I would like to do is just work with the object, before it was serialized to the file.

So let me illustrate my problem using code

public string TransformXMLFromObject(myObjType myobj , string xsltFileName)
{
     // Notice the xslt stays the same.
     // Its in these next few lines that I can't figure out how to load the xml document (xd) from an object, and not from a file....

     var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None };
     var xd = new XmlDocument();
     xd.Load(xtr);
}
7
  • 1
    I don't follow what you are wanting to do, can you post a better example? Commented Mar 30, 2010 at 21:05
  • change what so that you can pass in an object? The XmlTextReader? you want to pass an object to the XmlTextReader? And what do you expect to get out ? Commented Mar 30, 2010 at 21:09
  • 1
    @JL: you should not be using new XmlTextReader(). You should be using XmlReader.Create() instead. Commented Mar 30, 2010 at 21:14
  • @Cheeso, I want to load xd (the XMLDocument) from an object, not from file, the XMLTextReader is not important to me. Commented Mar 30, 2010 at 21:14
  • 1
    @John, any reason why new XMLTestReader is bad? Commented Mar 30, 2010 at 21:18

3 Answers 3

36

You want to turn an arbitrary .NET object into a serialized XML string? Nothing simpler than that!! :-)

public string SerializeToXml(object input)
{
   XmlSerializer ser = new XmlSerializer(input.GetType(), "http://schemas.yournamespace.com");
   string result = string.Empty;

   using(MemoryStream memStm = new MemoryStream())
   {
     ser.Serialize(memStm, input);

     memStm.Position = 0;
     result = new StreamReader(memStm).ReadToEnd();
   } 

   return result;
} 

That should to it :-) Of course you might want to make the default XML namespace configurable as a parameter, too.

Or do you want to be able to create an XmlDocument on top of an existing object?

public XmlDocument SerializeToXmlDocument(object input)
{
   XmlSerializer ser = new XmlSerializer(input.GetType(), "http://schemas.yournamespace.com");

   XmlDocument xd = null;

   using(MemoryStream memStm = new MemoryStream())
   {
     ser.Serialize(memStm, input);

     memStm.Position = 0;

     XmlReaderSettings settings = new XmlReaderSettings();
     settings.IgnoreWhitespace = true;

     using(var xtr = XmlReader.Create(memStm, settings))
     {  
        xd = new XmlDocument();
        xd.Load(xtr);
     }
   }

   return xd;
}
Sign up to request clarification or add additional context in comments.

10 Comments

@marc_s: ick! No using blocks! new XmlTextReader()! -1!
@John: I was just fixing the new XmlTextReader().... you're too quick to downvote......
@John: but explain to me in simple and easy to understand words the benefit of XmlReader.Create() vs. new XmlTextReader() - nobody has made a compelling point so far.....
@marc_s, quote from the doc: Although the Microsoft .NET Framework includes concrete implementations of the XmlReader class, such as the XmlTextReader, XmlNodeReader, and the XmlValidatingReader classes, in the .NET Framework version 2.0, we recommend that you create XmlReader instances using the Create method (msdn.microsoft.com/en-us/library/9khb6435.aspx). I guess the only compelling reason might be that if in .NET 7.9 they introduce the HyperXmlReader class you won't need to change your code to benefit from it :-)
@marc_s: in your second piece of code, it doesn't change anything. But in the first one, you're returning a string, so using a MemoryStream and then reading it with a StreamReader to obtain a string seems a bit overcomplicated... with a StringWriter, you get a string directly
|
31

You can serialize directly into the XmlDocument:

XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
using (XmlWriter w = nav.AppendChild())
{
    XmlSerializer ser = new XmlSerializer(typeof(MyType));
    ser.Serialize(w, myObject);
}

9 Comments

I think the ser.Serializer doesn't accept the object as a parameter?
uh, nice... and no intermediate string involved :)
If I wasn't clear enough, the code above doesn't compile because ser.Serialize has some invalid parameters. Otherwise it looks like an elegant solution.
But since it's not a proper benchmark, it may give a false idea of the performance.
@randomuser: no intermediate Stream or TextReader objects. If you only need those objects to construct the XmlDocument, then why bother with them?
|
16

Expanding on @JohnSaunders solution I wrote the following generic function:

public static XmlDocument SerializeToXml<T>(
            T source,
            XmlSerializerNamespaces namespaces = null)
{
    var document = new XmlDocument();
    var navigator = document.CreateNavigator();

    using var writer = navigator.AppendChild();
    var serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(writer, source, namespaces);
    
    return document;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.