如何从.NET对象创建XML文档?

时间:2010-03-30 21:02:29

标签: c# .net xml

我有以下接受文件名的变量:

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

我想改变它,以便我可以传入一个对象。我不想首先将对象序列化为文件。

这可能吗?

更新

我最初的意图是获取一个xml文档,合并一些xslt(存储在一个文件中),然后输出并返回html ...像这样:

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();
}

在上面的代码中,我正在从文件中读取xml。现在我想要做的就是在将对象序列化到文件之前使用它。

所以让我用代码

来说明我的问题
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);
}

3 个答案:

答案 0 :(得分:32)

您想将任意.NET对象转换为序列化XML字符串吗?没有比这更简单的了!! : - )

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;
} 

应该这样:-)当然,您可能希望将默认的XML命名空间配置为参数。

或者您希望能够在现有对象之上创建XmlDocument吗?

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;
}

答案 1 :(得分:22)

您可以直接序列化到XmlDocument

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

答案 2 :(得分:6)

扩展@JohnSaunders解决方案我编写了以下通用函数:

public XmlDocument SerializeToXml<T>(T source) {
    var document = new XmlDocument();
    var navigator = document.CreateNavigator();

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