XML
HTML旨在显示信息,而XML旨在传输信息。XML结构有:父节点、子节点和兄弟节点。
常用类型有:XElement、XDocument、XAttribute
XML语法规则
所有XML元素必须有关闭标签;对大小写敏感;必须包含根元素;XML注释,<!--This is a comment>
读取XML文件
加载文档:XDocument.Load()方法
获取直接子元素:Element方法与Elements方法
示例:
getRequestString("Flight.Booking.API.AutoBookRequest\\Flight.Booking.API.AutoBookRequest.xml");//getRequestString(@"Flight.Booking.API.AutoBookRequest\Flight.Booking.API.AutoBookRequest.xml");
public string getRequestString(string fileName)
{
XMLPath = string.Format("xml\\{0}", fileName);
string requestStr = XDocument.Load(XMLPath).ToString();//也可以先实例化
return requestStr;
}
IEnumerable、Descendants()、FirstOrDefault()
Descendants()返回XML文档或片段中的所有子元素(所有级别的子元素),开发人员常常从根元素开始处理XML文档,沿着元素和属性的树形结构向下查找,一直到叶节点一级。
FirstOrDefault - 返回集合中的第一个元素(如果没有则返回默认值)
示例:
public void SetRequestNode(string nodeLocalName,string value)
{
IEnumerable<XElement> temp = Request.Elements();
string[] nodeNameList = nodeLocalName.Split('\\');
foreach (string nodeName in nodeNameList)
{
//如果直接用nodeName作为参数传入p.Name.LocalName在循环的时候会有问题,所以设置string n来workaround
string n = nodeName;
temp = temp.Descendants().Where(p => p.Name.LocalName == n);
}
var result = temp.FirstOrDefault();
result.Value = value;
}
使用XElement类创建一个xml文档
XElement 类是 LINQ to XML 中的基础类之一。它表示一个 XML 元素。可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。
示例:
public static void CreateCategories()
{
string path = @"d:\website";
XElement root = new XElement("Categories",
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Beverages"),
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Condiments")
),
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "Condiments")
)
);
root.Save(path);
}
运行该示例将会得到一个xml文件,其内容为:
<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>
<CategoryName>Beverages</CategoryName>
</Category>
<Category>
<CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>
<CategoryName>Condiments</CategoryName>
</Category>
<Category>
<CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>
<CategoryName>Confections</CategoryName>
</Category>
</Categories>
XMLNode.attributes 属性
返回一个 XMLNodes 集合,该集合代表指定元素的属性。.
return xmlNode.Attributes["value"].Value;