tags:

views:

136

answers:

2

I have some xml like this:

  <Data>
      <Rows>
        <Row>
          <Field Name="title">Mr</Field>
          <Field Name="surname">Doe</Field>
        <Row>
      <Rows>
 <Data>

using linq how can I get the value contained in the field element where the attribute is surname

thanks

+1  A: 

Actually, you're trying to do an XML-to-Linq thing here. Linq to XML is more meant to create an XML structure from objects through Linq.

Since you have an XML file, you can use something like this:

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(Content);
        string Surname = xml.SelectSingleNode("//Field/[@Name='surname']").Value.ToString();

In other use, to get data from XML, use XPath instead.

Workshop Alex
I believe LINQ to XML is very much intended to be an alternative to XPath, offering strongly-typed support and a more intuitive query syntax.
Enrico Campidoglio
LINQ to XML adds another layer on top of the XML. Basically, what it does is translate your query to XPath constructions. Looking at the XQuery sample from http://msdn.microsoft.com/en-us/bb330936.aspx you can see how you can write a complex query in LINQ instead of XPath. LINQ is more intuitive for those who aren't experienced with XPath. That's true.
Workshop Alex
+2  A: 

Here is how you can express your query using LINQ to XML:

XDocument doc = XDocument.Parse("<Data><Rows><Row><Field Name=\"title\">Mr</Field><Field Name=\"surname\">Doe</Field></Row></Rows></Data>");
string[] matches = (from e in doc.Descendants("Field")
                    where (string)e.Attribute("Name") == "surname"
                    select (string)e).ToArray();
Enrico Campidoglio