将xml查询结果分配给变量

时间:2012-11-30 14:36:03

标签: c# xml linq variables

我的xml看起来像这样:

<x>
  <y a1= "abc" a2= "xyz" a3="2" a4="4" a5="8"/>
  <y a1= "def" a2= "hij" a3="5" a4="10" a5="15"/>
</x>

以下代码过滤my xml的值并将结果打印到屏幕:

    static void Main(string[] args)
            {
                int first;
                int second;
                int third;
                XDocument doc = XDocument.Load(xmlFile);
                IEnumerable<XElement> rows = from row in doc.Descendants("x")
                                             where row.Attribute("a1").ToString() == "abc" & row.Attribute("a2").ToString() == "xyz"
                                             select row;
                foreach (XElement ele in rows)
                {
                    IEnumerable<XAttribute> aList = from att in ele.DescendantsAndSelf().Attributes()
                                                    select att;
                    foreach (XAttribute xatr in atrList)
                    {
                        Console.WriteLine(att);
                    }
                }
            }
        }
    }

我不想将结果显示到屏幕上,而是将过滤行的值a3,a4和a5分配给变量first,second和third。我还想用新值覆盖a3,a4和a5的值。

2 个答案:

答案 0 :(得分:2)

static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(xmlFile);
            IEnumerable<XElement> rows = from row in doc.Descendants("x")
                                         where row.Attribute("a1").ToString() == "abc" & row.Attribute("a2").ToString() == "xyz"
                                         select row;

            int first;
            int second;
            int third;

            foreach (XElement ele in rows)
            {
                Int32.TryParse(ele.Attribute("a3").Value, out first);
                Int32.TryParse(ele.Attribute("a4").Value, out second);
                Int32.TryParse(ele.Attribute("a5").Value, out third);

                Console.WriteLine(string.Format("{0} {1} {2}", first, second, third);
            }
        }
    }
}

答案 1 :(得分:0)

您可以根据索引将它们设置为过滤后的行。用以下内容替换你的内部foeach()循环:

IEnumerable<XAttribute> aList = (from att in ele.DescendantsAndSelf().Attributes()
                                                    select att).ToList();
first = atrList[2];
second = atrList[3];
third = atrList[4];