C# 如何从XML返回的布尔值中获取值?
我想做一个函数来输入值(funName)并检查XML文件属性(funName),然后输出XML文件属性(isEnable)布尔值true或false 如何修改此代码 我的XML文件C# 如何从XML返回的布尔值中获取值?,c#,xml,C#,Xml,我想做一个函数来输入值(funName)并检查XML文件属性(funName),然后输出XML文件属性(isEnable)布尔值true或false 如何修改此代码 我的XML文件 <itema> <itemb FunName="ABC" isEnable="true"></itemb> <itemb FunName="DEF" isEnable="false"></itemb> </itema> 我的代码
<itema>
<itemb FunName="ABC" isEnable="true"></itemb>
<itemb FunName="DEF" isEnable="false"></itemb>
</itema>
我的代码
public bool FunEnable(string funName , string isEnable)
{
bool result = true;
XmlDocument xDL = new XmlDocument();
xDL.Load("C://XMLFile2.xml"); //Load XML file
XmlNode xSingleNode = xDL.SelectSingleNode("//itemb");
XmlAttributeCollection xAT = xSingleNode.Attributes; //read all Node attribute
for (int i = 0; i < xAT.Count; i++)
{
if (xAT.Item(i).Name == "isEnable")
{
Console.WriteLine(xAT.Item(i).Value); //read we want attribute content
}
}
return result;
}
public bool FunEnable(字符串funName,字符串isEnable)
{
布尔结果=真;
XmlDocument xDL=新的XmlDocument();
Load(“C://XMLFile2.xml”);//加载xml文件
XmlNode xSingleNode=xDL.SelectSingleNode(“//itemb”);
XmlAttributeCollection xAT=xSingleNode.Attributes;//读取所有节点属性
对于(int i=0;i
非常感谢嗯,我更喜欢Linq而不是XML
var xDoc = XDocument.Load(path);
bool result = (from itemb in xDoc.Descendants("itemb")
where itemb.Attribute("FunName").Value == funcName
select itemb.Attribute("isEnable").Value == "true")
.FirstOrDefault();
也许这一条有效:
public bool FunEnable(string funName, string isEnable)
{
bool result = true;
XDocument xDL = XDocument.Load("C://XMLFile2.xml");
var xSingleNode = from node in xDL.Descendants("itemb")
where node.Attribute("FunName").Value == funName
select node;
if(xSingleNode.Count() > 0)
{
result = xSingleNode.ElementAt(0).Attribute("isEnable").Value == "true";
//If there is at least one node with the given name, result is set to the first nodes "isEnable"-value
}
return result;
}
你可以试试这个:
public static bool FunEnable(string funNam)
{
bool result = true;
XmlDocument xDL = new XmlDocument();
xDL.Load(@"C:/XMLFile2.xml"); //Load XML file
XmlNodeList nodeList = xDL.SelectNodes("//itemb");
foreach (XmlNode node in nodeList)
{
if (node.Attributes["FunName"].Value.Equals(funNam))
{
result = Convert.ToBoolean(node.Attributes["isEnable"].Value);
break;
}
}
Console.WriteLine("with funName = "+ funNam +" isEnable equal to : " + result);
return result;
}
输出
funName=ABC时,isEnable等于:True
使用LINQ到XML相当简单。您可以使用
XDocument.load
加载文档,然后获得isEnable
值,如下所示:
var result = doc.Descendants("itemb")
.Where(e => (string)e.Attribute("FunName") == "ABC")
.Select(e => (bool)e.Attribute("isEnable"))
.Single();
您可以在这里看到一个工作演示:您必须使用XmlDocument吗?LINQ到XML使这变得很简单。。。(无可否认,从您得到的代码中获得结果并不困难-目前打印的是什么?这行不是:
XmlNode xSingleNode=xDL.SelectSingleNode(//itemb”)
不总是返回第一个itemb元素?对于XDocument,您会得到一个异常,即:在创建XML文件时,不能将非空白字符添加到内容中