关于xml中读取节点值的研究!
这几天网上看到一个弄绑定下拉菜单的,后来自己就想弄一个读xml绑定的,结果读节点一直没想出来,今天偶然看了一下以前写的东西,居然发现了端倪。
下面为xml文件
下面为xml文件
<?xml version="1.0" encoding="gb2312"?>
<China>
<State id="0" name="请选择">
<City>请选择</City>
</State>
<State id="1" name="江西">
<City>九江</City>
<City>南昌</City>
<City>庐山</City>
<City>景德镇</City>
</State>
<State id="2" name="北京">
<City>北京西</City>
<City>居庸关</City>
<City>清华园</City>
<City>周口店</City>
</State>
<State id="3" name="福建">
<City>福州</City>
<City>厦门</City>
<City>漳州</City>
</State>
<State id="4" name="甘肃">
<City>兰州</City>
<City>洛门</City>
<City>嘉峪关</City>
</State>
<State id="5" name="广东">
<City>广州</City>
<City>深圳</City>
<City>东莞</City>
<City>石牌</City>
</State>
<State id="6" name="安徽">
<City>合肥</City>
<City>黄山</City>
<City>九龙岗</City>
<City>马鞍山</City>
</State>
</China>
下面为只读节点值State里面的name<China>
<State id="0" name="请选择">
<City>请选择</City>
</State>
<State id="1" name="江西">
<City>九江</City>
<City>南昌</City>
<City>庐山</City>
<City>景德镇</City>
</State>
<State id="2" name="北京">
<City>北京西</City>
<City>居庸关</City>
<City>清华园</City>
<City>周口店</City>
</State>
<State id="3" name="福建">
<City>福州</City>
<City>厦门</City>
<City>漳州</City>
</State>
<State id="4" name="甘肃">
<City>兰州</City>
<City>洛门</City>
<City>嘉峪关</City>
</State>
<State id="5" name="广东">
<City>广州</City>
<City>深圳</City>
<City>东莞</City>
<City>石牌</City>
</State>
<State id="6" name="安徽">
<City>合肥</City>
<City>黄山</City>
<City>九龙岗</City>
<City>马鞍山</City>
</State>
</China>
1 XmlDocument doc=new XmlDocument();
2 doc.Load(Server.MapPath("info.xml"));
3 XmlNodeList nodeList=doc.SelectSingleNode("China").ChildNodes;
4 string result="";
5 foreach(XmlNode xn in nodeList)//遍历所有子节点
6 {
7 XmlElement xe=(XmlElement)xn;
8 result=result+xe.GetAttribute("name");//这里就是把节点的name的值取出来
9 }
下面是读取某一个节点下的子节点,这里用到了一个过滤的功能2 doc.Load(Server.MapPath("info.xml"));
3 XmlNodeList nodeList=doc.SelectSingleNode("China").ChildNodes;
4 string result="";
5 foreach(XmlNode xn in nodeList)//遍历所有子节点
6 {
7 XmlElement xe=(XmlElement)xn;
8 result=result+xe.GetAttribute("name");//这里就是把节点的name的值取出来
9 }
1 XmlDocument doc=new XmlDocument();
2 doc.Load(Server.MapPath("info.xml"));
3 XmlNodeList nodeList=doc.SelectSingleNode("descendant::State[@id='2']").ChildNodes;//这里就是过滤,只取State中id为2的节点下的子节点
4 string result="";
5 foreach(XmlNode xn in nodeList)//遍历所有子节点
6 {
7 XmlElement xe=(XmlElement)xn;
8 result=result+xe.InnerText;//这里就是子节点的值
9 }
现在弄出来了觉得很是简单,呵呵。上面的descendant::State[@id='2']里面还可以根据深度加如果city下还有一个country,可以查descendant::State[City/Country='xxx']这里就是查的State下面的City下的Country=xxx的这一个。
2 doc.Load(Server.MapPath("info.xml"));
3 XmlNodeList nodeList=doc.SelectSingleNode("descendant::State[@id='2']").ChildNodes;//这里就是过滤,只取State中id为2的节点下的子节点
4 string result="";
5 foreach(XmlNode xn in nodeList)//遍历所有子节点
6 {
7 XmlElement xe=(XmlElement)xn;
8 result=result+xe.InnerText;//这里就是子节点的值
9 }