C#中可以用XmlDocument类操作Xml文件
Xml文件格式较多,一种为较复杂的 在<> 中添加元素数据的,一种为在<></>中添加元素数据的
<?xml version="1.0" encoding="utf-8" ?> <root> <person name="WangYao"> <age>25</age> </person> <person name="Jobs"> <age>56</age> </person> </root>
C#控制台中读取
XmlDocument doc = new XmlDocument(); doc.Load(Environment.CurrentDirectory+"\\Test.xml"); XmlElement rootElem = doc.DocumentElement; XmlNodeList personNodes = rootElem.GetElementsByTagName("person"); foreach (XmlNode node in personNodes) { string strName = ((XmlElement)node).GetAttribute("name"); //获取name属性值 Console.WriteLine(strName); XmlNodeList subAgeNodes = ((XmlElement)node).GetElementsByTagName("age"); //获取age子XmlElement集合 if (subAgeNodes.Count == 1) { string strAge = subAgeNodes[0].InnerText; Console.WriteLine(strAge); } } Console.ReadKey();
XmlElement 类中有GetElementsByTagName(string name)函数可以访问所有与name参数匹配的节点元素集合,返回的是XmlNodeList类型,由于XmlNodeList继承IEnumerable接口,所以可以用foreach遍历在此程序中 rootElem.GetElementsByTagName("person") 等价于 rootElem.ChildNodes ((XmlElement)node).GetAttribute("name") 等价于 node.Attributes["name"].Value ((XmlElement)node).GetElementsByTagName("age")[0].InnerText 等价于 node.ChildNodes[0].InnerTextXmlNode没有获取元素集合的GetAttribute方法所以强转换XmlElement类型((XmlElement)node).GetAttribute("name")和node.Attributes["name"].Value获取<person name="WangYao"> 中制定名称的特定的值。如果匹配到返回string类型变量。GetElementsByTagName返回XmlElement集合。匹配到有1个结果则Count为1。((XmlElement)node).GetElementsByTagName("age")[0].InnerText和node.ChildNodes[0].InnerText获取<age>25</age>中age元素的值 Environment.CurrentDirectory获取和设置当前目录该进程从中启动的目录的完全限定目录。获取的路径为当前项目的bin/debug目录
//((XmlElement)node).GetAttribute("name") 等价于 node.Attributes["name"].Value
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-font-kerning:1.0pt;}