C# 读取XML每个节点的值
XML文档结构如下:
<?xml version="1.0" encoding="utf-8"?>
<packet>
<proto name="1" showname="1">
<field name="1-1" showname="1-1" show="1-1"/>
<field name="1-2" showname="1-2" show="1-2"/>
<field name="1-3" showname="1-3" show="1-3"/>
<field name="1-4" showname="1-4" show="1-4"/>
</proto>
<proto name="2" showname="2">
<field name="2-1" showname="2-1" show="2-1"/>
<field name="2-2" showname="2-2" show="2-2"/>
<field name="2-3" showname="2-3" show="2-3"/>
<field name="2-4" showname="2-4" show="2-4"/>
<field name="2-5" showname="2-5" show="2-5"/>
<field name="2-6" showname="2-6" show="2-6"/>
<field name="2-7" showname="2-7" show="2-7"/>
<field name="2-8" showname="2-8" show="2-8"/>
</proto>
<proto name="3" showname="3">
<field name="3-1" showname="3-1" show="3-1">
<field name="3-1-1" showname="3-1-1" show="3-1-1"/>
<field name="3-1-2" showname="3-1-2" show="3-1-2"/>
<field name="3-1-3" showname="3-1-3" show="3-1-3"/>
</field>
<field name="3-2" showname="3-2" show="3-2">
<field name="3-2-1" showname="3-2-1" show="3-2-1"/>
<field name="3-2-2" showname="3-2-2" show="3-2-2"/>
<field name="3-2-3" showname="3-2-3" show="3-2-3"/>
</field>
</proto>
<proto name="4" showname="4">
<field name="4-1" value="4-1"/>
<field name="4-2" showname="4-2" show="4-2">
<file name="4-2-1" showname="4-2-1" show="4-2-1"/>
</field>
</proto>
</packet>
C#读取该XML每个节点的showname 和 show的值, 没有要读取value的值,我被循环弄混头脑,希望得到帮助...谢谢
------解决方案--------------------C# code
读:
//打开某文件(假设web.config在根目录中)
string filename=Server.MapPath("/") + @"WebApplication1\web.config";
XmlDocument xmldoc= new XmlDocument();
xmldoc.Load(filename);
//得到顶层节点列表
XmlNodeList topM=xmldoc.DocumentElement.ChildNodes;
foreach(XmlElement element in topM)
{
if(element.Name.ToLower()=="appsettings")
{
//得到该节点的子节点
XmlNodeList nodelist=element.ChildNodes;
if ( nodelist.Count >0 )
{
//DropDownList1.Items.Clear();
foreach(XmlElement el in nodelist)//读元素值
{
//DropDownList1.Items.Add(el.Attributes["key"].InnerXml);
//this.TextBox2.Text=el.Attributes["key"].InnerText;
this.TextBox2.Text=el.Attributes["key"].Value;
this.Label1.Text=el.Attributes["value"].Value;
//同样在这里可以修改元素值,在后面save。
// el.Attributes["value"].Value=this.TextBox2.Text;
}
}
}
}
xmldoc.Save(filename);
}
效果:
<appSettings>
<add key="密码" value="admin" />
<add key="ltp" value="first" /