1

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

以下代码过滤我的 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 的值。

4

2 回答 2

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);
            }
        }
    }
}
于 2012-11-30T14:44:41.807 回答
0

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

IEnumerable<XAttribute> aList = (from att in ele.DescendantsAndSelf().Attributes()
                                                    select att).ToList();
first = atrList[2];
second = atrList[3];
third = atrList[4];
于 2012-11-30T14:38:17.957 回答