KF-SoftwareDev
KF-SoftwareDev

Reputation: 403

How can I select specific elements from an XML using Linq to Xml?

How can I pick out the Fields from the following XML using LINQ:

<MESSAGE MSGID="123" NAME="MyMessage">
  <FIELDS>
    <FIELD NAME="F1" FTYPE="STRING">123</FIELD>
    <FIELD NAME="F2"> FTYPE="INT">0</FIELD>
  </FIELDS>
</MESSAGE>

Code:

XDocument xmldoc = null;

try
{
    xmldoc = XDocument.Parse(bstrXml);

    //Returns NULL
    //var result = xmldoc.Descendants("Fields");
    //Returns NULL
    //var result = xmldoc.Elements("Fields");
}

Upvotes: 0

Views: 93

Answers (2)

piyush
piyush

Reputation: 29

Elements with attribute Fields can be found using

var childElements = xDoc.Elements();
var fieldAttributes = childElements.Elements().Select(p => p.Attribute("Fields"));

Upvotes: 1

Stefan William-Worrall
Stefan William-Worrall

Reputation: 713

This solution will search for xml field elements and select a field by name

        var fieldName = "F1";
        var xDoc = XDocument.Load("XMLFile1.xml");
        var field = xDoc.Descendants("FIELD")
            .Where(f => string.Compare(f.Attribute("NAME").Value, fieldName, StringComparison.CurrentCulture) == 0);

Change the where expression to refine your search.

Upvotes: 0

Related Questions