<?xml version="1.0" encoding="utf-8" ?>
<xml>
<exception>
<modeule id="test1">
<tipMessage id="m001">连接数据库失败</tipMessage>
<tipMessage id="m002">删除失败</tipMessage>
</modeule>
<modeule id="test2">
<tipMessage id="m001">连接数据库失败</tipMessage>
<tipMessage id="m002">删除失败</tipMessage>
</modeule>
</exception>
<message>
<module id="test3">
<tipMessage id="m001">连接数据库失败</tipMessage>
<tipMessage id="m002">删除失败</tipMessage>
</module>
</message>
</xml>
以上为一个XML文件,我想根据我传入的参数“test1”和“m001”读出节点 <tipMessage id="m001">连接数据库失败</tipMessage>的值,高手请指点
引用XML,然后添加下面代码
public partial class testxml : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string a = GetStatus("test1", "m001");
Response.Write(a);
}
private string GetStatus(string modeule, string tipMessage)
{
string Result = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("xml/test.xml"));
XmlNode xmlNode = xmlDoc.SelectSingleNode("xml"); //取得xml下面的节点
foreach (XmlNode exMe in xmlNode)
{
if (exMe.SelectSingleNode("modeule") != null) //exception
{
XmlNode modeuleNode = exMe.SelectSingleNode("modeule");
if (modeuleNode.Attributes.GetNamedItem("id").InnerText.ToUpper() == modeule.ToUpper())
{
foreach (XmlNode tipMessageNode in modeuleNode)
{
if (tipMessageNode.Attributes.GetNamedItem("id").InnerText.ToUpper() == tipMessage.ToUpper())
{
Result = tipMessageNode.InnerText;
break;
}
}
}
}
else //message
{
XmlNode modeuleNode = exMe.SelectSingleNode("module");
if (modeuleNode.Attributes.GetNamedItem("id").InnerText.ToUpper() == modeule.ToUpper())
{
foreach (XmlNode tipMessageNode in modeuleNode)
{
if (tipMessageNode.Attributes.GetNamedItem("id").InnerText.ToUpper() == tipMessage.ToUpper())
{
Result = tipMessageNode.InnerText;
break;
}
}
}
}
}
return Result;
}
}
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace XmlTest
{
class Program
{
static void Main(string[] args)
{
var doc = XDocument.Load("data.xml");
var value = (from node in doc.Descendants("modeule")
where node.Attribute("id").Value == "test1"
from tip in node.Elements("tipMessage")
where tip.Attribute("id").Value == "m001"
select tip.Value).FirstOrDefault();
Console.WriteLine(value);
Console.ReadLine();
}
}
}
用GetAttribute(“id”)的值来判断,如果其值是test1,不就得到你要的节点,在看子节点是否符合。