C# 操作XML

-、XMLTextWriter用法

 

代码
   
     
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
// System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, null);
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Server.MapPath( " userInfo.xml " ), System.Text.Encoding.UTF8);

writer.Formatting
= System.Xml.Formatting.Indented;
writer.WriteStartDocument(
true );

writer.WriteStartElement(
" PP " );
writer.WriteStartElement(
" X " );
writer.WriteString(
" 1 " );
writer.WriteEndElement();
writer.WriteStartElement(
" Y " );
writer.WriteString(
" 1 " );
writer.WriteEndElement();
writer.WriteStartElement(
" Name " );
writer.WriteString(
" fan " );
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
writer.Close();
}


二、XMLDocument用法

 

代码
   
     
XmlDocument xmldoc;
XmlNode xmlnode;
xmldoc
= new XmlDocument();

xmlnode
= xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "" , "" );
xmldoc.AppendChild(xmlnode);
// 加入XML的声明段落,<?xml version="1.0" encoding="utf-8"?>
// xmlnode = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
// xmldoc.AppendChild(xmlnode);
// 加入一个根元素
xmldoc.AppendChild(xmldoc.CreateElement( "" , " Menu " , "" ));

foreach (ComponentArt.Web.UI.MenuItem mi in Menu2.Items)
{
if (mi.Enabled && mi.Visible)
{
XmlElement xmlelem;
xmlelem
= xmldoc.CreateElement( " Item " );
xmlelem.SetAttribute(
" title " , string .Format( " {0} " , mi.Text));

if ( string .IsNullOrEmpty(mi.NavigateUrl))
xmlelem.SetAttribute(
" url " , string .Format( " {0} " , mi.Items[ 0 ].NavigateUrl));
else
xmlelem.SetAttribute(
" url " , string .Format( " {0} " , mi.NavigateUrl));

xmldoc.ChildNodes.Item(
1 ).AppendChild(xmlelem);
}
}

xmldoc.Save(Request.PhysicalApplicationPath
+ @" data.xml " );
string xmlContent = xmldoc.OuterXml;

 

 

另外读取的话,用XMLTextReader很方式,也是只进读取,性能据说比较OK!
    三、XMLTextReader用法

 

代码
   
     
string targer;
XmlDocument xmldoc
= new XmlDocument();
xmldoc.Load(
" userInfo.xml " );
byte [] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(xmldoc.OuterXml);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes))
{
using (XmlTextReader reader = new XmlTextReader(stream))
{
while (reader.Read())
{
if ( ! reader.IsEmptyElement && reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case " X " :
targer
= reader.ReadString();
break ;
}
}
}
}
}

 


另外,XML的一个应用是序列化,要用到把字符串转化成byte数组,方法:
   byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(XmlContent); 
相对的,把byte数组转化为字符串的方法则为:
 string XmlContent = System.Text.UTFEncoding.UTF8.GetString(bytes);
这样方便了吧,把想存的东东转化为byte数组,然后压缩一下,网络传输的话也应该很OK了吧

你可能感兴趣的:(xml)