放分求一个XML遍历操作的最基础例子,谢谢大家!!
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<result>
<Acc>
<row id="1">
<fie value="f1">a1</fie>
<fie value="f2">a2</fie>
</row>
<row id="2">
<fie value="f1">b1</fie>
<fie value="f2">b2</fie>
</row>
……
</Acc>
</result>
</response>
以上是XML文档,要求遍历每个row,把row下的每个fie节点value值为"f2"的值如"a2,b2"等提取出来放到字符串中,如str = "a2,b2,……"
麻烦各位给个例子,谢谢了!!!!!
------解决方案--------------------
StringBuilder build = new StringBuilder ();
XmlDocument doc = new XmlDocument ();
doc.load(@"D:\1.xml");
XmlNodeList list = doc.DocumentElement.GetElementByName("row");
for(int i=0;i<list.count;i++)
{
for(int j=0;j<list[i].ChildNodes.count ;j++)
{
if(list[i].ChildNodes[j].Attributs["value"].value="f2")
{
build.Append( list[i].ChildNodes[j].innerText);
build.Append(",");
}
}
}
String s = build.ToString();
------解决方案--------------------
C# code
string str = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<response>
<result>
<Acc>
<row id=""1"">
<fie value=""f1"">a1 </fie>
<fie value=""f2"">a2 </fie>
</row>
<row id=""2"">
<fie value=""f1"">b1 </fie>
<fie value=""f2"">b2 </fie>
</row>
</Acc>
</result>
</response> ";
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
StringBuilder sb = new StringBuilder();
foreach(XmlNode rowNode in doc.GetElementsByTagName("row"))
{
if (rowNode.HasChildNodes)
{
foreach (XmlNode fieNode in rowNode.ChildNodes)
{
if (fieNode.Name == "fie" && fieNode.Attributes["value"].Value == "f2")
sb.Append(fieNode.InnerText + ",");
}
}
}
Console.WriteLine(sb.ToString().TrimEnd(','));