XML:可拓展的标记语言(跨平台数据表现)用于保存数据
XML:标记需要关闭 ;单根性
.NET中DOM常用对象:
XmlDocument :一个XML文档
XmlNode:xml中的单个节点
XmlNodeList:排序的节点集合
XmlElement:表示一个元素
XmlAttribute:表示一个属性
XmlAttributeCollection:元素节点的属性集合
XmlText:元素属性的文本类容
eg:
<students>
<student id="1" age="20">张三</student>
</students>
元素是XML文档的核心
XmlElement 表示XM文档中的元素节点 派生自XmlNode类
XmlElement常用属性:
Attributes:获取一个XmlAttributeCollection,包含该元素的所有属性
ChildNodes:所有子节点
NodeType:节点类型
Value:节点值
解析XML
//实例化一个xmlDocument对象 XmlDocument doc = new XmlDocument();
//服务器路径
string path = Server.MapPath(@"~\class.xml");
//加载xmlDocument
doc.Load(path);
//得到文档根节点
XmlNode root = doc.DocumentElement;
string info = "";
foreach (XmlNode item in root.ChildNodes)
{
foreach (XmlNode itemc in item.ChildNodes)
{
info += itemc.Value + "<br/>";
}
}
Response.Write(info);
写入XML:
//创建xml文档描述
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
//创建根节点
XmlNode root = doc.CreateNode(XmlNodeType.Element, "students", null);
//子节点
XmlNode class1 = doc.CreateNode(XmlNodeType.Element, "student", null);
//文档节点
XmlNode clasName = doc.CreateNode(XmlNodeType.Text, null, null);
//赋值
clasName.Value = "赵六";
//属性节点
XmlAttribute classCa = doc.CreateAttribute("stuNo");
classCa.Value = "004";
XmlAttribute classAge = doc.CreateAttribute("age");
classAge.Value = "20";
class1.AppendChild(clasName); class1.Attributes.Append(classCa); class1.Attributes.Append(classAge);
root.AppendChild(class1);
doc.AppendChild(root);
string mathX = Server.MapPath(@"~\class.xml");
doc.Save(mathX);
JSON:轻量级的数据交换格式(容易阅读和编写,利于机器解析和生成)
JSON构成:键值对的集合
eg:
{"name":"张三","age":20,....}
数组: {"students":[{},{}]}
JSON的序列化与反序列化:
引入命名空间:using system.Runtime.Serialization,Json;
实例化:
JavaScriptSerializer js = new JavaScriptSerializer();
反序列化: js.Deserialize();
序列化: js.Serialize();
XML与JSON对比:
1,客户端:json更容易被序列化为javascript对象
2,服务器:传输的是xml字符串,
3,安全性:json容易携带恶意代码
4,性能:json没有多种标记,解析起来更快
5,验证:xml更成熟