用c#生成xml字串及解析xml字串

gagaghost發表於2007-05-17

生成xml字串:

using (StringWriter sw = new StringWriter())
{
XmlTextWriter xtw = new XmlTextWriter(sw);

xtw.WriteStartDocument();

xtw.WriteStartElement("root");

//test
xtw.WriteStartElement("test");
xtw.WriteString("test content");
xtw.WriteEndElement();

xtw.WriteEndElement();//root
xtw.WriteEndDocument();

result = sw.ToString();
}

解析xml:

using System;
using System.IO;
using System.Text;
using System.Xml;

namespace foo {
public class bar {
public static void Main() {
Test1();
Test2();
Test3();

}

public static void Test1() {
string strInput = "";
XmlTextReader r = new XmlTextReader(new StringReader(strInput));
StringBuilder sb = new StringBuilder();
XmlTextWriter w = new XmlTextWriter(new StringWriter(sb));
w.WriteNode(r, false);
w.Flush();
string strOutput = sb.ToString();
Console.WriteLine("Input = {0}, Output = {1}", strInput.Length, strOutput.Length);
}

public static void Test2() {
string strInput = "";
XmlTextReader r = new XmlTextReader(new StringReader(strInput));
MemoryStream ms = new MemoryStream();
XmlTextWriter w = new XmlTextWriter(ms, Encoding.Unicode);
w.WriteNode(r, false);
w.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string strOutput = sr.ReadToEnd();
Console.WriteLine("Input = {0}, Output = {1}", strInput.Length, strOutput.Length);
}

public static void Test3() {
string strInput = "";
XmlTextReader r = new XmlTextReader(new StringReader(strInput));
MemoryStream ms = new MemoryStream();
XmlTextWriter w = new XmlTextWriter(ms, Encoding.UTF8);
w.WriteNode(r, false);
w.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string strOutput = sr.ReadToEnd();
Console.WriteLine("Input = {0}, Output = {1}", strInput.Length, strOutput.Length);
}

}
}

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/5859/viewspace-915389/,如需轉載,請註明出處,否則將追究法律責任。

相關文章