如何从XML返回布尔值获取值?

问题描述:

我想要输入值(funName)并检查XML文件属性(FunName),然后输出XML文件属性(isEnable)boolean true或false如何从XML返回布尔值获取值?

如何修改此代码?

我的XML文件

<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; 
} 

非常感谢

+0

你*有*使用XmlDocument的? LINQ to XML使这个微不足道的...(不可否认,从你已经得到的代码中得到结果并不难 - –

+0

不是这行: 'XmlNode xSingleNode = xDL.SelectSingleNode( “// itemb”);'不是总是返回第一个itemb元素? –

那么你可以试试这个:

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等于:真

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(); 
+0

以及XDocument,您将得到一个异常,它表示:创建XML文件时不能将非空白字符添加到内容 –

嗯,我喜欢的LINQ to XML ..

也许这一个作品:

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; 
    } 

使用LINQ to XML这非常简单。您可以使用XDocument.Load加载文档,然后得到像这样的isEnable值:

var result = doc.Descendants("itemb") 
    .Where(e => (string)e.Attribute("FunName") == "ABC") 
    .Select(e => (bool)e.Attribute("isEnable")) 
    .Single(); 

这里你可以看到一个工作演示:https://dotnetfiddle.net/MYTOl6