1

I don't know too much about this subject yet, so I'm open to any suggestions that lead to my end goal...

  1. I receive an XML string from a web service
  2. I would like to load the string into a C# class capable of being used for LINQ
  3. I would like to be able to extract an array of all "someentity" instances in the XML using LINQ with that class.

Here's some sample XML I made up with the someentity example:

<replydata>
    <someentity>
        <role id="1234" roletype="2" />
        <history length="24" accessstr="http://someurl" />
    </someentity>
    <someentity>
        <role id="1235" roletype="2" />
        <history length="30" accessstr="http://someurl2" />
    </someentity>
    ... keep repeating for a while
</replydata>

Is this possible, and if so, can someone provide a simple example or direct me to the right place to find one?

John Humphreys
  • 37,047
  • 37
  • 155
  • 255

2 Answers2

2

You can do it like this:

var responseString =
    @"<replydata>
        <someentity>
            <role id=""1234"" roletype=""2"" />
            <history length=""24"" accessstr=""http://someurl"" />
        </someentity>
        <someentity>
            <role id=""1235"" roletype=""2"" />
            <history length=""30"" accessstr=""http://someurl2"" />
        </someentity>
    </replydata>";
var response = XElement.Load(new StringReader(responseString));
var someentitys = response.Elements("someentity");
foreach(var e in someentitys) {
    Console.WriteLine(
        "Role: {0}, access: {1}"
    ,   e.Element("role").Attribute("roletype")
    ,   e.Element("history").Attribute("accessstr")
    );
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

The class you're looking for here is XDocument

http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx

You can create an XDocument from an XML String using it's Parse() method and then use LINQ to query that document.

Here's an article that demos its LINQ Capabilities

http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html

Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157