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

时间:2015-09-04 08:34:10

标签: c# xml

我想输入值(funName)并检查XML文件属性(FunName)然后输出XML文件属性(isEnable)布尔值true或false

如何修改此代码?

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

非常感谢

4 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

好吧,我更喜欢Linq和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;
    }

答案 3 :(得分:0)

你可以试试这个:

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

输出

  

with funName = ABC isEnable等于:True