日期:2014-05-17  浏览次数:20449 次

请问怎么查询XML文件中节点的值?
大家好,比如有个XML文件A.xml,内容为:
<?xml version="1.0" encoding="utf-8"?>
<Group>
  <Type>
  <ID>1</ID>
  <Name>MyName 1</Name>
  </Type>
  <Type>
  <ID>2</ID>
  <Name>MyName 2</Name>
  </Type>
  <Type>
  <ID>3</ID>
  <Name>MyName 3</Name>
  </Type>
</Group>

当ID=1时,查询出节点Name的值MyName 1;当ID=2时,查询出节点Name的值MyName 2等等,要怎么写代码呢?先谢谢大家了。

------解决方案--------------------
XmlDocument doc = new XmlDocument();
doc.LoadXml("文件");
doc.GetElementsByTagName("节点")[0].InnerText
------解决方案--------------------
http://www.68design.net/Development/Aspnet/Basis-AspNet/11369-1.html

获取数据之后过滤下就可以了

LINQ XML
------解决方案--------------------
C# code

            XmlDocument doc = new XmlDocument();
            doc.Load("e:\\1.txt");
            XmlNodeList nodes = doc.DocumentElement.SelectNodes("Type");
            foreach (XmlNode node in nodes)
            {
                //node.InnerText,这个就是name的内容,自己判断
            }

------解决方案--------------------
string Name1="";
string Name2 = "";
string Name3 = "";
string xmlstr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
xmlstr += "<Group><Type><ID>1</ID><Name>MyName 1</Name></Type><Type><ID>2</ID><Name>MyName 2</Name></Type><Type><ID>3</ID><Name>MyName 3</Name></Type></Group>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstr);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("Type");
for (int i = 0; i < nodes.Count; i++)
{
XmlNode xmlnode =nodes.Item(i);
switch(xmlnode.SelectSingleNode("ID").InnerText)
{
case "1": Name1 = xmlnode.SelectSingleNode("Name").InnerText; break;
case "2": Name2 = xmlnode.SelectSingleNode("Name").InnerText; break;
case "3": Name3 = xmlnode.SelectSingleNode("Name").InnerText; break;
default: break;
}
}
//Name
------解决方案--------------------
找ID为1的节点:
XmlNode incrementPidUploadNode = domIncrementIndex.SelectSingleNode("/Group/Type/ID[text()='" + 1 + "']");
然后找下个节点,取值便可