I am trying to parse this XML document -
<?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
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;}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.