C#里如何将XML格式字符串转成XML文件?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#里如何将XML格式字符串转成XML文件?相关的知识,希望对你有一定的参考价值。
例如:将"<annotation><appinfo>schools.xsd v3.0 2002-07</appinfo><documentation xml:lang="en">GML schema for GML2 Schools example; change to schoolMember element for GML3.2.1</documentation></annotation>"转为:
<annotation>
<appinfo>schools.xsd v3.0 2002-07</appinfo>
<documentation xml:lang="en">
example; change to schoolMember element for GML3
.2.1</documentation>
</annotation>
---------------------
我转为XML文件的目的是为了能在TreeView显示,如果无需中间的环节,能将这个字符串加到一个TreeView控件里也可以
dom.LoadXml(字符串);
dom.save(文件名); 参考技术A XmlDocument doc = new XmlDocument();
doc.LoadXml("xml string");
//XmlDocument可以从文件加载,也可以从字符串、数据流加载 参考技术B 不懂
一个可序列化的C#对象,如何转成一个XML格式的文件或字符串
原文:http://blog.csdn.net/otong/article/details/7894059
序列化或反序列化成一个字符串:
方法一:
序列化:
- public static string XMLSerialize<T>(T entity)
- {
- StringBuilder buffer = new StringBuilder();
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- using (TextWriter writer = new StringWriter(buffer))
- {
- serializer.Serialize(writer, entity);
- }
- return buffer.ToString();
- }
反序列化:
- public static T DeXMLSerialize<T>(string xmlString)
- {
- T cloneObject = default(T);
- StringBuilder buffer = new StringBuilder();
- buffer.Append(xmlString);
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- using (TextReader reader = new StringReader(buffer.ToString()))
- {
- Object obj = serializer.Deserialize(reader);
- cloneObject = (T)obj;
- }
- return cloneObject;
- }
方法二:
- /// <summary>
- /// 对象序列化成 XML String
- /// </summary>
- public static string XmlSerialize<T>(T obj)
- {
- string xmlString = string.Empty;
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- using (MemoryStream ms = new MemoryStream())
- {
- xmlSerializer.Serialize(ms, obj);
- xmlString = Encoding.UTF8.GetString(ms.ToArray());
- }
- return xmlString;
- }
- /// <summary>
- /// XML String 反序列化成对象
- /// </summary>
- public static T XmlDeserialize<T>(string xmlString)
- {
- T t = default(T);
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
- {
- using (XmlReader xmlReader = XmlReader.Create(xmlStream))
- {
- Object obj = xmlSerializer.Deserialize(xmlReader);
- t = (T)obj;
- }
- }
- return t;
- }
如果要序列化到一个文件,则使用FileStream就可以了
如:
string strFile = @"c:/book.xml";
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter.Serialize(fs, entity);
}
附:其实还可以直接用SringWriter
StringBuilder sb = new StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter .Serialize(writer,entity );
以上是关于C#里如何将XML格式字符串转成XML文件?的主要内容,如果未能解决你的问题,请参考以下文章
C# XML文件和XML格式字符串(string类型)的互相转换