简体   繁体   English

使用 C# LINQ 解析 XML 文档

[英]Parse an XML document using C# LINQ

I am trying to parse this XML document -我正在尝试解析此 XML 文档-

<?xml version="1.0" encoding="UTF-8"?>
<Data xmlns:data="report">
   <Report>
      <GroupName Descriptor="Administrator">
         <ID type="ID">1</ID>
         <ID type="Group">Administrator</ID>
      </GroupName>
      <Members Name="12345 / john smith ">
         <ID type="ID">1</ID>
         <ID type="UserID">12345</ID>
         <ID type="UserName">jsmith</ID>
      </Members>
   </Report>
   <Report>
      <GroupName Descriptor="User">
         <ID type="ID">1</ID>
         <ID type="Group">User</ID>
      </GroupName>
      <Members Name="14568/Bob smith">
         <ID type="ID">1</ID>
         <ID type="UserID">14568</ID>
         <ID type="UserName">bsmith</ID>
      </Members>
      <Members Name="14597/Tommy lee">
         <ID type="ID">1</ID>
         <ID type="UserID">14597</ID>
         <ID type="UserName">tlee</ID>
      </Members>
   </Report>
</Data>

I want list of users, something like -我想要用户列表,例如 -

jsmith Administrator
bsmith User
tlee   User

I tried Xpath and Descendants both didn't yield me the results I wanted我试过 Xpath 和后代都没有给我我想要的结果

Try following:尝试以下操作:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<Group> groups = doc.Descendants("Report").Select(x => new Group()
            {
                groupName = (string)x.Element("GroupName").Attribute("Descriptor"),
                userNames = x.Elements("Members").Select(y => (string)y.Attribute("Name")).ToArray()
            }).ToList();
        }
    }
    public class Group
    {
        public string groupName { get; set; }
        public string[] userNames { get;set;}
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM