Reputation: 497
Below is the XML I am trying to parse. I need to extract the DLRNUMBER tag from the first FL nodelist (first one). I am trying to use Xdocument. I don't know the syntax to get the tag.
XDocument xdoc = XDocument.Load(@"C:\Temp\FR_in.xml");
var query = from e in xdoc.Descendants("FLSS")
select e;
Below is the XML:
<PACK Id="NI">
<PROP Id="KEY1" Val="NI_NY" />
<PROP Id="SOURCE" Val="NI" />
<PROP Id="TARGET" Val="NY" />
<REQUEST Id="CREATE_FR">
<PROP Id="PROID" Val="LIBRARY.OBJECT" />
<DOBJ Id="FH"> <ATTR Id="PAYTYPE" Val="WR" />
<ATTR Id="DTREATED" Val="3/20/2018" />
<ATTR Id="DUEDATE" Val="3/20/2018" />
<ATTR Id="AMOUNT" Val="1499.5" />
<ATTR Id="SOURCE" Val="DS" />
<ATTR Id="CREATOR" Val="DSI" />
<ATTR Id="APPROVER" Val="UF03567" />
<COLL Id="FLSS">
<FL>
<DOBJ Id="FL_1">
<ATTR Id="ACCTNUMBER" Val="162101" />
<ATTR Id="CENTER" Val="506" />
<ATTR Id="DLRNUMBER" Val="48" />
<ATTR Id="DLR" Val="58D" />
<ATTR Id="PAYEE" Val="58D" />
<ATTR Id="PAYMENTTYPE" Val="WR" />
<ATTR Id="AMOUNT" Val="1499.5" />
</DOBJ>
<DOBJ Id="FL_2">
<ATTR Id="ACCTNUMBER" Val="194061" />
<ATTR Id="CENTER" Val="506" />
<ATTR Id="DLRNUMBER" Val="48" />
<ATTR Id="DLR" Val="58D" />
<ATTR Id="PAYEE" Val="58D" />
<ATTR Id="PAYMENTTYPE" Val="WR" />
<ATTR Id="AMOUNT" Val="1499.5" />
</DOBJ>
</FL>
</COLL>
</DOBJ>
</REQUEST>
</PACK>
Upvotes: 0
Views: 49
Reputation: 34421
Try following. I prefer to get all items in an array so I can select one or more items as needed. :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication31
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement fl = doc.Descendants("FL").FirstOrDefault();
int[] dlrNumbers = fl.Elements("DOBJ").Select(x => x.Elements("ATTR").Where(y => (string)y.Attribute("Id") == "DLRNUMBER").Select(y => (int)y.Attribute("Val"))).SelectMany(y => y).ToArray();
}
}
}
Upvotes: 0
Reputation: 43876
In Descendants
you have to provide the XName
of the nodes to search for. In your code example you try to search for a value of an attribute of a node.
You can do this:
var result = xdoc.Descendants("ATTR")
.FirstOrDefault(element =>
element.Attribute("Id")?.Value == "DLRNUMBER")?.Attribute("Val")?.Value;
This finds the first ATTR
tag that has an Id
attribute with the value DLRNUMBER
and returns the value of its Val
attribute.
If there may be other DLRNUMBER
values at different levels that you don't want to find, you can consider to find the COLL
node first:
var collNode = xdoc.Descendants("COLL").FirstOrDefault();
var result = collNode.Descendants("ATTR")
.FirstOrDefault(element =>
element.Attribute("Id")?.Value == "DLRNUMBER")?.Attribute("Val")?.Value;
or refine the search according to your requirements and the kind of xml you expect as input.
Upvotes: 2