c# /XML:读取给定元素索引的属性值

本文关键字:索引 元素 属性 XML 读取 | 更新日期: 2023-09-27 18:18:45

我有以下不可更改的XML文件:

<products>
    <product>
        <attributes>
            <att name="Name" value="TOTO" />
            <att name="Surname" value="Toto" />
            <att name="Age" value="10" />
        </attributes>
    </product>
    <product>
        <attributes>
            <att name="Name" value="TATA" />
            <att name="Surname" value="Tata" />
            <att name="Age" value="20" />
        </attributes>
    </product>
    <product>
        <attributes>
            <att name="Name" value="TITI" />
            <att name="Surname" value="Titi" />
            <att name="Age" value="30" />
        </attributes>
    </product>
</products>

使用c#,我需要提取字段的节点值等于NameAge,在给定的索引。很好的例子:输入2将返回一个包含TITI的字符串和另一个包含30的字符串。

目前,我使用XmlDocument来加载XML文件,并使用带有GetElementsByTagName方法的XmlNodeList来获取所有属性;然后,我可以显示这些元素,但我不能只显示其中的两个,这取决于属性名称和索引。

充其量,我需要一个方法,如myXmlNodeList.Node["att"]. attributes ["Name"]. atindex (x).

有人能帮我吗?

c# /XML:读取给定元素索引的属性值

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<products>" +
                    "<product>" +
                        "<attributes>" +
                            "<att name='"Name'" value='"TOTO'" />" +
                            "<att name='"Surname'" value='"Toto'" />" +
                            "<att name='"Age'" value='"10'" />" +
                        "</attributes>" +
                    "</product>" +
                    "<product>" +
                        "<attributes>" +
                            "<att name='"Name'" value='"TATA'" />" +
                            "<att name='"Surname'" value='"Tata'" />" +
                            "<att name='"Age'" value='"20'" />" +
                        "</attributes>" +
                    "</product>" +
                    "<product>" +
                        "<attributes>" +
                            "<att name='"Name'" value='"TITI'" />" +
                            "<att name='"Surname'" value='"Titi'" />" +
                            "<att name='"Age'" value='"30'" />" +
                        "</attributes>" +
                    "</product>" + 
                "</products>";
            XElement products = XElement.Parse(xml);
            var results = products.Elements("product").Select(x => new
            {
                name = x.Descendants("att").Where(y => y.Attribute("name").Value == "Name").Select(z => z.Attribute("value").Value).FirstOrDefault(),
                age = x.Descendants("att").Where(y => y.Attribute("name").Value == "Age").Select(z => (int)z.Attribute("value")).FirstOrDefault()
            }).ToList();
            string name = results[2].name;
            int age = results[2].age;
        }
    }

}
​