-3

您能帮我了解如何使用 C# 的属性获取 xml 标记的值吗?需要:

代码示例

<Friend>
   <FName>Patrick</FName>
   <LName>Aston</LName>
   <Age>22</Age>
   <FriendsIdList>
       <FriendId IdType="school">29982252</FriendId>
       <FriendId IdType="athome">2334568</FriendId>
       <FriendId IdType="atcamp">9908787</FriendId>
       <FriendId IdType="studygroup">6588432</FriendId>
   </FriendsIdList>
</Friend>

如何获取标记的值 <FriendId IdType="XXXXX">XXXXXX</FriendId> 我尝试将 XMLnodelist 用于 foreach 序列,但没有成功。你有什么建议吗?谢谢你的帮助。

4

1 回答 1

0

使用字典尝试 xml linq 以获取 Id

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication51
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("Friend").Select(x => new {
                fName = (string)x.Element("FName"),
                lName = (string)x.Element("LName"),
                age = (int)x.Element("Age"),
                ids = x.Descendants("FriendId")
                   .GroupBy(y => (string)y.Attribute("IdType"), z => (string)z)
                   .ToDictionary(y => y.Key, z => z.FirstOrDefault())
            }).ToList();



        }
    }


}

在此处输入图像描述

于 2018-07-12T10:00:35.690 回答